从另一个构造函数调用构造函数?

时间:2011-12-01 22:07:43

标签: c++ oop constructor

我创建了三个类:Shape(基类),RectangleSquare。我尝试从ShapeRectangle的构造函数中调用Square的构造函数,但编译器显示错误。

以下是代码:

class Shape{
public:
    double x;
    double y;
    Shape(double xx, double yy) {x=xx; y=yy;}
    virtual void disply_area(){
        cout<<"The area of the shape is: "<<x*y<<endl;
    }
};
class Square:public Shape{
public:
    Square(double xx){ Shape(xx,xx);}
    void disply_area(){
        cout<<"The area of the square is: "<<x*x<<endl;
    }
};
class Rectnagel:public Shape{
    public:
        Rectnagel(double xx, double yy){ Shape(xx,yy);}
    void disply_area(){
        cout<<"The area of the eectnagel is: "<<x*y<<endl;
    }
};
int main() {
    //create objects
    Square      sobj(3);
    Rectnagel   robj(3,4);
    sobj.disply_area();
    robj.disply_area();
    system("pause");;//to pause console screen, remove it if u r in linux
    return 0;
}

修改代码的任何想法或建议?

2 个答案:

答案 0 :(得分:7)

要从孩子构建基础,请执行以下操作

//constructor
child() : base()   //other data members here
{
     //constructor body
}

在你的情况下

class Rectangle : public Shape{
    public:
        Rectangle(double xx, double yy) : Shape(xx,yy)
        {}

    void display_area(){
        cout<<"The area of the eectnagel is: "<<x*y<<endl;
    }
};

答案 1 :(得分:4)

这是正确的方法:

class Square:public Shape{
public:
    Square(double xx) : Shape(xx,xx){}
    void disply_area(){
        cout<<"The area of the square is: "<<x*x<<endl;
    }

};

查找superclass constructor calling rules