C ++上派生派生类的初始化列表

时间:2017-03-27 03:45:28

标签: c++

我无法弄清楚如何为派生派生类的构造函数实现初始化列表。请参阅基础抽象类:

public:
Shape(char *Type = "Unknown")       
{
    this->Type = Type;
}

string getType() {return Type;}

当然有一个派生的Rectangle类,易于实现:

public:
Rectangle(double Side1, double Side2) : Shape("Rectangle")
{
    this->Side1 = Side1;    
    this->Side2 = Side2;
}

然后我想将Square作为一个特例来导出Rectangle,但对于我的生活,我无法弄清楚如何包含假定的初始化列表{{1} }在下一个派生的Shape("Square")类上:

Square

我无法再次使用冒号操作员,可以。任何帮助,非常感谢。 我的最终目标是在cpp上查询两个派生类的类型,我实例化如下:

public:
Square(double Size) : Rectangle(Size, Size) { }

并检索:

Shape *rectangle = new Rectangle(dSide1, dSide2);   
Shape *square = new Square(dSide1);     

2 个答案:

答案 0 :(得分:2)

除了@n.m.的答案之外,另一种方法是将Type声明为受保护的成员,并在子类的构造函数中直接初始化它:

class Shape {
public:
    Shape()
    {
        Type = "Unknown";
    }

    string getType() { return Type; }

protected:
    string Type;
};

class Rectangle : public Shape
{
public:
    Rectangle(double Side1, double Side2)
    {
        this->Side1 = Side1;
        this->Side2 = Side2;
        Type = "Rectangle";
    }

protected:
    double Side1;
    double Side2;
};

class Square : public Rectangle
{
public:
    Square(double Size) : Rectangle(Size, Size) 
    { 
        Type = "Square";
    }
};

答案 1 :(得分:1)

有两种方式。

  1. 使用虚拟继承。

    class Shape {
    public:
      Shape(char *Type = "Unknown")       
    
    class Rectangle: public virtual Shape {
    public:
      Rectangle(double Side1, double Side2) : Shape("Rectangle")
    
    class Square: public Rectangle, public virtual Shape {
    public:
      Square(double Size) : Rectangle(Size, Size), Shape ("Square") 
    
  2. 向所有构造函数添加类型参数:

    class Shape {
    public:
      Shape(char *Type = "Unknown")       
    
    class Rectangle: public Shape {
    public:
      Rectangle(double Side1, double Side2, char *Type = "Rectangle") : Shape(Type)
    
    class Square: public Rectangle {
    public:
      Square(double Size, char *Type = "Square") : Rectangle(Size, Size, Type)
    
  3. 不建议在班级中使用类型字段(类型为whartever)。如果您需要人类可读的tyoe名称用于显示目的,请使用虚拟功能

    class Shape {
      // this should be an abstract class
      public: virtual const char* type() = 0;
    
    class Rectangle : public Shape {
      public: virtual const char* type() {
        return "Rectangle";
      }
    

    不要将这些功能用于其他事情,特别是用于确定程序逻辑。