当我在下面的代码中调用 f1 时,是否应该调用构造函数? 我在对象 b(f1 的参数)中看到“this”指针不同,这意味着创建了一个新对象,但我没有在 b 的构造函数中看到打印。 但是有对析构函数的调用,谁能解释一下?
class A
{
int k ;
public:
A(int i)
{
k=i;
printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this);
}
~A()
{
printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this);
}
void A_fn()
{
printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this);
}
};
void f1(A b)
{
b.A_fn();
}
int _tmain(int argc, _TCHAR* argv[])
{
A a(10);
f1(a);
return 0;
}
vc++ 2012 中显示的输出:
10 inside [A::A]ptr[00B3FBD0]
10 inside [A::A_fn]ptr[00B3FAEC]
10 inside [A::~A]ptr[00B3FAEC]
10 inside [A::~A]ptr[00B3FBD0]
Press any key to continue . . .
最佳答案
因为当您按值传递对象时,该对象被复制,因此将调用复制构造函数。
关于c++ - 将对象传递给函数不会导致构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44321535/