码迷,mamicode.com
首页 > 编程语言 > 详细

C++虚复制构造函数

时间:2014-04-29 17:26:52      阅读:522      评论:0      收藏:0      [点我收藏+]

标签:des   com   http   class   blog   style   div   img   code   java   javascript   

构造函数不能是虚函数。但有时候确实需要能传递一个指向基类对象的指针,并且有已创建的派生类对象的拷贝。通常在类内部创建一个Clone()方法,并设置为虚函数。

 

mamicode.com,码迷
//Listing 12.11 Virtual copy constructor
#include <iostream>
using namespace std;

class Mammal
{
  public:
     Mammal():itsAge(1) { cout << "Mammal constructor...\n"; }
     virtual ~Mammal() { cout << "Mammal destructor...\n"; }
     Mammal (const Mammal & rhs);
     virtual void Speak() const { cout << "Mammal speak!\n"; }
     virtual Mammal* Clone() { return new Mammal(*this); }
     int GetAge()const { return itsAge; }
  protected:
     int itsAge;
};

Mammal::Mammal (const Mammal & rhs):itsAge(rhs.GetAge())
{
   cout << "Mammal Copy Constructor...\n";
}

class Dog : public Mammal
{
  public:
    Dog() { cout << "Dog constructor...\n"; }
    virtual ~Dog() { cout << "Dog destructor...\n"; }
    Dog (const Dog & rhs);
    void Speak()const { cout << "Woof!\n"; }
    virtual Mammal* Clone() { return new Dog(*this); }
};

Dog::Dog(const Dog & rhs):
Mammal(rhs)
{
   cout << "Dog copy constructor...\n";
}

class Cat : public Mammal
{
  public:
    Cat() { cout << "Cat constructor...\n"; }
    ~Cat() { cout << "Cat destructor...\n"; }
    Cat (const Cat &);
    void Speak()const { cout << "Meow!\n"; }
    virtual Mammal* Clone() { return new Cat(*this); }
};

Cat::Cat(const Cat & rhs):
Mammal(rhs)
{
   cout << "Cat copy constructor...\n";
}

enum ANIMALS { MAMMAL, DOG, CAT};
const int NumAnimalTypes = 3;
int main()
{
   Mammal *theArray[NumAnimalTypes];
   Mammal* ptr;
   int choice, i;
   for ( i = 0; i<NumAnimalTypes; i++)
   {
      cout << "(1)dog (2)cat (3)Mammal: ";
      cin >> choice;
      switch (choice)
      {
        case DOG:   ptr = new Dog;
                   break;
        case CAT:   ptr = new Cat;
                   break;
        default:   ptr = new Mammal;
                   break;
      }
      theArray[i] = ptr;
   }
   Mammal *OtherArray[NumAnimalTypes];
   for (i=0;i<NumAnimalTypes;i++)
   {
      theArray[i]->Speak();
      OtherArray[i] = theArray[i]->Clone();
   }
   for (i=0;i<NumAnimalTypes;i++)
      OtherArray[i]->Speak();
   return 0;
}
mamicode.com,码迷

输出结果:

(1)dog (2)cat (3)Mammal: 3
Mammal constructor...
Woof!
Mammal Copy Constructor...
Dog copy constructor...
Meow!
Mammal Copy Constructor...
Cat copy constructor...
Mammal speak!
Mammal Copy Constructor...
Woof!
Meow!
Mammal speak!

C++虚复制构造函数,码迷,mamicode.com

C++虚复制构造函数

标签:des   com   http   class   blog   style   div   img   code   java   javascript   

原文地址:http://www.cnblogs.com/findumars/p/3698133.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!