#include <iostream>
#include <string>
using namespace std;
class Dog
{
private:
string nm;
public:
Dog(const string& name) : nm(name)
{
cout << "Creating Dog: " << *this << endl;
}
~Dog()
{
cout << "Deleting Dog: " << *this << endl;
}
Dog(const Dog* dp, const string& msg) : nm(dp->nm + msg)
{
cout << "Creating Dog: " << *this << " from " << *dp << endl;
}
void rename(const string& newName)
{
nm = newName;
cout << "Dog renamed to: " << *this << endl;
}
friend ostream& operator<<(ostream& os, const Dog& d)
{
return os << "[" << d.nm << "]";
}
};
class DogHouse
{
private:
Dog* p;
string houseName;
public:
DogHouse(Dog* dog, const string& house) :p(dog), houseName(house)
{
}
DogHouse(const DogHouse& dh) :p(new Dog(dh.p, " copy-constructed")), houseName(dh.houseName + " copy-constructed")
{
} // 这个就是深复制,创建了一个新的(Dog)指针,
DogHouse& operator=(const DogHouse& dh)
{
if (&dh != this)
{
p = new Dog(dh.p, " assigned");
houseName = dh.houseName + " assigned";
}
return *this;
}
~DogHouse()
{
delete p;
cout << "析构函数, " << endl;
}
Dog* getDog() const
{
return p;
}
void rename(const string& newName)
{
houseName = newName;
}
friend ostream& operator<<(ostream& os, const DogHouse& dh)
{
return os << "[" << dh.houseName << "] constains " << *dh.p;
}
};
int main()
{
DogHouse d1(new Dog("Fee"), "FeeHouse");
cout << d1 << endl << endl;
d1.getDog()->rename("Fee2");
cout << d1 << endl << endl;
d1.rename("Fee2House");
cout << d1 << endl << endl;
//DogHouse d2 = d1; // 调用复制构造函数,
//d2.getDog()->rename("Tree");
//d2.rename("TreeHouse"); // C++默认的就是浅复制,
//cout << d1 << endl; // 这里只是浅复制,在更改后TreeHouse不相同,但是rename是相同的,
//cout << d2 << endl << endl;
DogHouse d2 = d1;
d2.getDog()->rename("Tree");
d2.rename("TreeHouse");
cout << d1 << endl;
cout << d2 << endl << endl;
//DogHouse d2 = d1;
//d1 = d2; // 调用重载构造函数,
cout << "hello" << endl;
d1 = d2;
cout << d1 << endl;
cout << d2 << endl;
cout << "xiu gai hou ," << endl;
d1.getDog()->rename("xiao cui");
d1.rename("xiao cui house");
cout << d1 << endl;
cout << d2 << endl;
// 当用到了指针的时候才使用深复制,没有用到指针就不分浅复制和深复制,
return 0;
}
重载赋值运算符2
最新推荐文章于 2024-04-25 18:40:56 发布