Mah*_*esh 1 c++ copy-constructor
我不明白为什么在这种情况下不会调用复制构造函数.有人可以解释一下吗?
#include <iostream>
class foo
{
int* ptr;
public:
foo()
{
std::cout << "\n Constructor \n" ;
ptr = new int;
*ptr = 10;
}
foo( const foo* &obj ) // Copy Constructor
{
std::cout << "\n Copy Constructor \n" ;
ptr = new int;
*(this->ptr) = *(obj->ptr);
}
// Copy Assignment Operator
~foo() // Destructor
{
delete ptr;
}
};
int main()
{
foo* objOne = new foo;
foo* objTwo = objOne ;
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
因为你只是创建另一个指针到同一个对象,而不是一个新的对象:
foo* objOne = new foo;
foo* objTwo = objOne;
^
|
+-- these are pointers.
Run Code Online (Sandbox Code Playgroud)
如果您想要一个新对象,请使用以下内容:
foo objTwo = objOne;
Run Code Online (Sandbox Code Playgroud)
并修复您的复制构造函数:
foo (const foo &obj) ...
Run Code Online (Sandbox Code Playgroud)
以下代码段显示了一种方法:
#include <iostream>
class foo {
public:
foo () {
std::cout << "constructor" << std::endl;
ptr = new int;
*ptr = 10;
}
foo (const foo &obj) {
std::cout << "copy constructor" << std::endl;
ptr = new int;
*(this->ptr) = *(obj.ptr);
}
~foo () {
delete ptr;
}
private:
int* ptr;
};
int main()
{
foo objOne;
foo objTwo = objOne ;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这输出:
constructor
copy constructor
Run Code Online (Sandbox Code Playgroud)
正如你所料.