#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次。
本文通过一个C++示例程序对比了对象按值传递和按引用传递的不同行为,并观察构造函数的调用次数,帮助理解C++中不同参数传递方式的影响。
261

被折叠的 条评论
为什么被折叠?



