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;