是否可以使用基类构造函数使用派生类将值初始化为基类私有成员?

时间:2018-02-28 22:35:25

标签: c++

我想要做的是使用width类设置height类的ShapeRectangle变量。

Shape.h

class Shape
{
    public:
        Shape(int x, int y);
    private:
        int width;
        int height;
};

Shape.cpp

Shape::Shape(int x, int y): width(x), height(y)
{
}

Rectangle.h

class Rectangle: public Shape
{
    public:
        Rectangle(int, int);
};

Rectangle.cpp

Rectangle::Rectangle(int x, int y):Shape(x, y)
{
}

Main.cpp的

int main()
{
    Rectangle rec(10,7);
    return 0;
}

我想要做的是使用rec对象初始化私有的类width的{​​{1}}和height变量。有没有办法做到这一点?或者我是否需要将Shapewidth变量设置为受保护?

2 个答案:

答案 0 :(得分:1)

您当前的Rectangle实现使用其参数正确调用基础构造函数。使用现代C ++(至少是C ++ 11),使用inheriting constructors可以简化Rectangle的实现:

struct Rectangle : public Shape {
    using Shape::Shape;
};

要访问private成员,需要将其更改为public,或者需要在基类中实现getter方法。或者,您可以创建private成员protected并在派生类中实现getter(尽管,因为height对于所有派生类是通用的,所以将getter放在基类)。

class Shape {
/* ... */
public:
    int get_height() const { return height; }
};
std::cout << rec.get_height() << std::endl;

答案 1 :(得分:0)

您的代码已编译正常,但您无法访问主函数中的rec.height,因为它是私有的。

公共继承的派生类可以访问基类的公共构造函数。

int main()
{
    Rectangle rec(10,7);
    // cout << rec.height << endl;  <----------- disabled
    return 0;
}