Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 是否可以使用基类构造函数使用派生类初始化基类私有成员的值?_C++ - Fatal编程技术网

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

C++ 是否可以使用基类构造函数使用派生类初始化基类私有成员的值?,c++,C++,我想做的是使用矩形类设置形状类的宽度和高度变量 形状.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) { } 矩形.h class Rectangle: public Shape { public

我想做的是使用
矩形
类设置
形状
类的
宽度
高度
变量

形状.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)
{
}
矩形.h

class Rectangle: public Shape
{
    public:
        Rectangle(int, int);
};
矩形.cpp

Rectangle::Rectangle(int x, int y):Shape(x, y)
{
}
Main.cpp

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

我想做的是使用
rec
对象初始化类
Shape
width
height
变量,这些变量是私有的。有办法吗?还是需要将
宽度
高度
变量设置为受保护

您的代码已经可以正常编译,除了您不能在主函数中访问
rec.height
,因为它是私有的

以公共方式继承的派生类可以访问基于该类的公共构造函数

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

/cOut您当前的代码<矩形> /Cord>的正确使用参数调用基本构造函数。使用现代C++(至少C++ 11),使用

可以简化<代码>矩形< /代码>的实现。 要访问
private
成员,需要将其更改为
public
,或者需要在基类中实现一个getter方法。或者,您可以使
private
成员
受保护
并在派生类中实现getter(虽然,由于所有派生类都有
height
,所以将getter放在基类中是合适的)


std::您的代码中是否已经这样做了。但是您不能这样打印它,因为它是
private
@HolyBlackCat。我这样做时会出错。
error:'int Shape::width'是private
。很抱歉打印语句。我刚刚意识到。@royK您发布的代码(编辑后)是正确的,不会生成任何错误您无法访问派生类中的私有成员,或者将它们声明为受保护的,或者将公共API编写为setter函数即使删除该行,我也会遇到相同的错误。我使用的是代码块。这是软件可能存在的问题吗?抱歉。我刚刚意识到了这一点。我使用的是CodeBlo你到底在哪里编译代码的?@royK,在
ubuntu
上使用了
gcc
compiler(g++)。
struct Rectangle : public Shape {
    using Shape::Shape;
};
class Shape {
/* ... */
public:
    int get_height() const { return height; }
};
std::cout << rec.get_height() << std::endl;