gpt4 book ai didi

c++ - 多级继承成员访问

转载 作者:搜寻专家 更新时间:2023-10-31 00:10:50 25 4
gpt4 key购买 nike

我在学OOP,好像遇到了问题。
代码:

class line {
protected:
double a;
public:

line() {a = 1;}
line(double var1) {a = var1;}
};

class rectangle: private line {
protected:
double b;
public:
double area() {return a * b;}

rectangle():line() {b = 1;}
rectangle(double var1):line(var1) {b = var1;}
rectangle(double var1, double var2):line(var1) {b = var2;}
};

class parallelepiped: private rectangle{
private:
double c;
public:
double volume() {return area() * c;}
void print() { cout << "Parallelepiped rectangle information:" << endl;
cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
cout << "Volume: " << volume() << endl << endl;}

parallelepiped():rectangle() {c = 1;}
parallelepiped(double var1):rectangle(var1) {c = var1;}
parallelepiped(double var1, double var2):rectangle(var1) {c = var2;}
parallelepiped(double var1, double var2, double var3):rectangle(var1, var2) {c = var3;}
};

问题:错误:'double line::a' 在 print() 中受到保护。
有什么方法可以打印出“a”,以及给学习者的一般提示吗?

最佳答案

在 C++ 中学习 OOP 时,您不需要使用私有(private)继承。在某些情况下,私有(private)或 protected 继承是不错的设计决策,但刚开始时并非如此。

如果你想访问父类(super class)的成员,你应该使用公共(public)继承

class rectangle: public line {};
class parallelepiped: public rectangle {};

下面是关于私有(private)公有继承和 protected 继承之间差异的 SO 解释:

Difference between private, public, and protected inheritance

关于c++ - 多级继承成员访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36196272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com