|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#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";
}
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));
obj1 = obj2; //复制
obj1.print();
obj2.print();
std::cout<<"-----------------------------\n";
/* Myclass obj3(new int(3));
Myclass obj4 = obj3;
obj3.print(); 这一段代码编译时候会出现程序错误,把它注释点就能编译了
obj4.print(); 是不是上面副本构造球有问题,还请大神指教;我用的是vc6.0 编译的
std::cout<<"------------------------------\n";
*/
Myclass obj5(new int(5));
obj5 = obj5;
obj5.print();
return 0;
}
请大神指教
|
|