函数参数中const 引用 和 传值
2008-09-13 14:14
295 查看
#include <iostream>
using namespace std;
class Object
{
public:
Object(int i = 1) { n = i; cout << "Object::Object()" << endl; }
Object(const Object& a)
{
n = a.n;
cout << "Object::Object(const Object&)" << endl;
}
~Object() { cout << "Object::~Object()" << endl; }
void inc() { ++n; }
int val() const { return n; }
private:
int n;
};
void foo(Object a)
{
cout << "enter foo, before inc(): inner a = " << a.val() << endl;
//a.inc();
cout << "enter foo, after inc(): inner a = " << a.val() << endl;
}
int main()
{
Object a;
cout << "before call foo : outer a = " << a.val() << endl;
foo(a);
cout << "after call foo : outer a = " << a.val() << endl;
return 0;
}
可以进行测试便得知,传引用只需要调用构造函数一次,而传值需要2次。
using namespace std;
class Object
{
public:
Object(int i = 1) { n = i; cout << "Object::Object()" << endl; }
Object(const Object& a)
{
n = a.n;
cout << "Object::Object(const Object&)" << endl;
}
~Object() { cout << "Object::~Object()" << endl; }
void inc() { ++n; }
int val() const { return n; }
private:
int n;
};
void foo(Object a)
{
cout << "enter foo, before inc(): inner a = " << a.val() << endl;
//a.inc();
cout << "enter foo, after inc(): inner a = " << a.val() << endl;
}
int main()
{
Object a;
cout << "before call foo : outer a = " << a.val() << endl;
foo(a);
cout << "after call foo : outer a = " << a.val() << endl;
return 0;
}
可以进行测试便得知,传引用只需要调用构造函数一次,而传值需要2次。
相关文章推荐
- 函数形参参数:const对象,const指针 const引用 实例
- Python 函数参数引用(传值/传址)/copy/deepcopy
- Python 函数参数引用(传值/传址)/copy/deepcopy
- php函数:函数的参数(传值与传引用)
- 【转载】用const修饰函数 以及引起的附加限制:const函数不能调用非const的函数或引用非const参数
- const引用做形参---函数参数的传递,并不都是复制
- 函数传递const和非const非引用参数的笔记 - 20150905
- C++ const类型引用做函数参数
- 作为函数参数的临时变量的引用必须是const的
- Python 函数参数引用(传值/传址)/copy/deepcopy
- python中函数参数的引用和传值
- Java函数参数的“传值”与“传引用”
- 位运算+引用+const+new/delete+内联函数、函数重载、函数缺省参数
- 常引用,const引用的案例,以及常引用作函数参数
- const引用和函数占位参数遇上默认参数以及内联函数
- Python 函数参数引用(传值/传址)/copy/deepcopy
- delphi 函数参数传递 默认参数(传值)、var(传址)、out(输出)、const(常数)四类
- 函数参数之 传常引用(passed by reference to const)替换 传值(passed by value)
- C++关于参数为const引用类型的函数调用参数成员函数的一个问题
- 函数参数之 传常引用(passed by reference to const)替换 传值(passed by value)