Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15270886
  • 博文数量: 7460
  • 博客积分: 10434
  • 博客等级: 上将
  • 技术积分: 78178
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-02 22:54
文章分类

全部博文(7460)

文章存档

2011年(1)

2009年(669)

2008年(6790)

分类: C/C++

2008-05-30 22:32:18

问题来由:
// 类中指针:如果一个对象包含了指向另外一个对象的指针,简单地拷贝一个指针意味着以指向相同的单元
// 的对象而结束。这个时候容易出问题,比如一个指针修改对象的同时,也修改了别人的对象了。
// 最直接的解决办法:========》拷贝这个指针所涉及的一切。 
举例说明:
注明:这里有两个类,Dog, DogHouse,每当创建一个DogHouse类对象的时候,都要相应地在其中产生一个new Dog.具体实现如下。
#include 
#include 
using namespace std;
//class Dog;
class Dog {
      string nm;
public:
 Dog(const string& name) : nm(name) {
       cout << \"Creating Dog...:  \" << *this < }
 //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 < }
 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 <<\"[\" < }
 };
////////////////////////////////
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\");

[NextPage]

 baby2.renameHouse(\"baby2sHouse\");
 cout << baby2 << endl;
 //operator=
 baby1 = baby2;
 cout << baby1 << endl;
 return 0;
}

阅读(567) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~