This is a question about c++ inheritance and factor

Asked 2 years ago, Updated 2 years ago, 65 views

The result I want is Position = (300, 300), [Rectangle] Size = (100, 100) I tried to make it sloppy with the power of c++ Newbie, but it was not enough. In addition to using virtual functions, the process of handing over factors is a mess, so I don't know where to ask you, but I'll work hard to pick out the necessary parts.

First of all

class Shape{
public:
    float x, y;
    Shape(float ix, float iy) {
        x = ix;
        y = iy;
    }
    virtual void Draw() {
        cout << "Position = ( " << x << ", " << y << " )";
    }
};

This is the Shape class. A class that represents the location of the shape and will be a parent class of another class.

class Rect : public Shape{
    float width, height;
    Rect(float x, float y, float w, float h) : Shape(x, y) {
        x = x;
        y = y;
        width = w;
        height = h;
    }
    void Draw() override 
    { 
        cout << "[Rectangle]" << "Size = ( " << width << ", " << height << " )"<< endl;
    }

};

This is the Rect class that inherits the Shape class above. After inheriting the shape here, I want to use x and y to represent the position, but I don't know how to use it after receiving the factor in the main function that I'll show you later.

And lastly,

void main() {
    Shape* shapes[5] = { NULL };
    shapes[0] = new Rect(300, 300, 100, 100);

    shapes[0]->Draw();

    delete shapes[0];
    shapes[0] = NULL;
}

This is the main function. There was an error, maybe because of the factors I handed over to Rect.

It's a terrible skill, but if you tell me, I want to be able to teach someone again by listening carefully and studying hard.

c++ class

2022-09-20 11:06

1 Answers

The reason for the error in the main function is that the constructor function cannot be accessed from the main function because the inside of the Rect class is not public. Please add public as below.

You can do the desired result like the Draw function below.

class Rect : public Shape {
public:
    float width, height;
    Rect(float x, float y, float w, float h) : Shape(x, y) {
        x = x;
        y = y;
        width = w;
        height = h;
    }
    void Draw() override
    {
        Shape::Draw();
        cout << ", ";
        cout << "[Rectangle]" << "Size = ( " << width << ", " << height << " )" << endl;
    }
};


2022-09-20 11:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.