问题来由:
// 类中指针:如果一个对象包含了指向另外一个对象的指针,简单地拷贝一个指针意味着以指向相同的存储单元
// 的对象而结束。这个时候容易出问题,比如一个指针修改对象的同时,也修改了别人的对象了。
// 最直接的解决办法:========》拷贝这个指针所涉及的一切。
举例说明:
注明:这里有两个类,Dog, DogHouse,每当创建一个DogHouse类对象的时候,都要相应地在其中产生一个new Dog.具体实现如下。
#include <iostream>
#include <string>
using namespace std;
//class Dog;
class Dog {
string nm;
public:
Dog(const string& name) : nm(name) {
cout << \"Creating Dog...: \" << *this <<endl;
}
//create a dog from a dog pointer:
Dog(const Dog* dp, const string& msg )
: nm(dp->nm + msg) {
cout << \"Copied dog...: \" << *this << \"from \"
<< *dp << endl;
}
~Dog() {
cout << \"Deleting Dog...:\" << *this <<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:
class DogHouse {
Dog* p;
string houseName;
public:
DogHouse(Dog* dog, const string& house) [Page]
: p(dog),houseName(house) { }
//c-c
DogHouse(const DogHouse& dh)
: p(new Dog(dh.p, \"copy-constructed\")),
houseName(dh.houseName + \"copy-constructed\") {}
//operator=
DogHouse& operator=(const DogHouse& dh) {
if(this != &dh){
p = new Dog(dh.p, \"assigned \");
houseName = dh.houseName + \" assigned\";
}
return *this;
}
//renameDogH
void renameHouse(const string& newName) {
houseName = newName;
}
Dog* getDog() const {
return p;
}
//~
~DogHouse() {
delete p;
}
//overload operator<<
friend ostream&
operator<<(ostream& os, const DogHouse& dh) {
return os <<\"[\" <<dh.houseName <<\"] contains \" << *dh.p;
}
};
////////////////////////////////
int main(int argc, char* argv[])
{
DogHouse baby1(new Dog(\"baby1\"), \"baby1sHouse\");
cout << baby1 << endl;
//call c-c
DogHouse baby2 = baby1;
cout << baby2 << endl;
baby2.getDog()->rename(\"baby2ForTest\");