yglskfj 发表于 2014-6-5 20:47:01

关于C++副本构造器求助

#include <iostream>
#include <string>
class MyClass
{
public:
MyClass(int *p);
MyClass(const MyClass &rhs);
~MyClass();
MyClass &operator=(const MyClass &rhs);
void print();
private:
int *ptr;
};
MyClass::MyClass(int *p)
{
std::cout << "进入主构造器\n";
ptr = p;
std::cout << "离开主构造器\n";
}
MyClass::MyClass(const MyClass &rhs)
{
std::cout << "进入副本构造器\n";
*this = rhs;
std::cout << "离开副本构造器\n";
}
MyClass::~MyClass()
{
std::cout << "进入析构器\n";
delete ptr;
std::cout << "离开析构器\n";
}
MyClass &MyClass::operator=(const MyClass &rhs)
{
std::cout << "进入赋值语句重载\n";
if( this != &rhs )
{
delete ptr;
ptr = new int;
*ptr = *rhs.ptr;
}
else
{
std::cout << "赋值号两边为同个对象,不做处理!\n"; //obj1 =obj1;
}
std::cout << "离开赋值语句重载\n";
return *this;
}
void MyClass::print()
{
std::cout << *ptr << std::endl;
}
int main()
{
MyClass obj1(new int(1));
MyClass obj2(new int(2));
obj2 = obj1;
obj1.print();
obj2.print();
std::cout << "----------------------------------------------\n";
MyClass obj3(new int(3));
MyClass obj4 = obj3;
obj3.print();
obj4.print();
std::cout << "----------------------------------------------\n";
MyClass obj5(new int(5));
obj5 =obj5;
obj5.print();
return 0;
}
兄弟们帮看看上面代码,副本构造器的。编译能过但一运行就出现Debug Assertion Failed???

oggplay 发表于 2014-6-5 20:50:18

我帮你运行了一下,不知道是不是这个结果。

yglskfj 发表于 2014-6-6 15:00:53

呃,,是这个结果。。我用的是VC6.0。。。与这有关吗?

santaclaus 发表于 2014-6-6 16:04:31

谁搞的翻译呀,copy constructor 叫副本构造器,感觉很别扭。
其实里面就是复制动作,感觉上“复制构造函数”或“拷贝构造函数”更顺一点。。
页: [1]
查看完整版本: 关于C++副本构造器求助