簡體   English   中英

從另一個構造函數調用構造函數?

[英]Calling constructor from another constructor?

我創建了三個類: Shape (基類), RectangleSquare 我試圖從RectangleSquare的構造函數調用Shape的構造函數,但是編譯器顯示錯誤。

這是代碼:

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;
}

有任何修改代碼的想法或建議嗎?

要從孩子那里建一個基地,請執行以下操作

//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;
    }
};

這是正確的方法:

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

};

查找超類構造函數調用規則

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM