使用基类对象来表示其派生类对象

pur*_*rga 2 c++

我需要一种方法让单个变量表示从同一基类派生的两种对象.

这有点难以描述,但我会尽力而为:

说基类:

class Rectangle
{
   float w;
   float h;
   const float area() {return w*h;}
};
Run Code Online (Sandbox Code Playgroud)

以及两个派生类:

class Poker : Rectangle
{
    int style;  // Diamond, Club, ....
    int point;  // A~10, J, Q, K
};

class BusinessCard : Rectangle
{
    string name;
    string address;
    string phone;
};
Run Code Online (Sandbox Code Playgroud)

现在可以声明一个对象,可以是扑克牌还是名片?

'因为下面的用法是非法的:

Rectangle* rec;
rec = new Poker();
delete rec;
rec = new BusinessCard();
Run Code Online (Sandbox Code Playgroud)

多态可能是一种方式,但由于它只对改变基类的成员属性有好处,我需要这个对象能够准确地表示任何一个派生对象.

编辑:

谢谢你的所有答案.公共继承,虚拟析构函数甚至boost :: variant typedef都是很棒的提示.

Meh*_*ari 8

你可以做到这一点.问题是类的继承修饰符是private.大多数情况下,private继承不是您想要使用的.相反,将其明确声明为public:

class Rectangle
{
   float w;
   float h;
   const float area() {return w*h; }; // you missed a semicolon here, btw
   virtual ~Rectangle() { } // to make `delete` work correctly
};

class Poker : public Rectangle // note the public keyword
{
    int style;  // Diamond, Club, ....
    int point;  // A~10, J, Q, K
};

class BusinessCard : public Rectangle 
{
    string name;
    string address;
    string phone;
};
Run Code Online (Sandbox Code Playgroud)

然后你的代码片段应该工作.