简体   繁体   中英

Calling constructor from another constructor?

I created three classes: Shape (base class) , Rectangle and Square . I tried to call Shape 's constructor from Rectangle 's and Square 's constructors, but the compiler shows errors.

Here is the code:

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

Any ideas or suggestion to modify the code?

To construct a base from a child you do the following

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

In your case

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

This is the correct way to do it:

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

};

Look up the superclass constructor calling rules .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM