公有继承中的公有方法在 C++ 中变为私有[已关闭]

问题描述 投票:0回答:1

我有一个带有公共方法的基类,但是当我尝试从从基类公开继承的派生类调用它时,它变成了私有方法。这怎么可能?公共继承不应该意味着公共方法保持公共吗?

这些是基类,我所指的方法就是具体的方法

r()

class Potential {
public:
    Potential() {}
    double r() const {return 0;}
};

这是派生类

class HammachePotential : public Potential {
public:
private:
    double r;
};

int main()
{
    HammachePotential a;
    a.r();
}

编辑: 编译器输出是

<source>:16:7: error: 'double HammachePotential::r' is private within this context
   16 |     a.r();
      |       ^
<source>:10:12: note: declared private here
   10 |     double r;
      |            ^
<source>:16:8: error: expression cannot be used as a function
   16 |     a.r();
      |     ~~~^~

我很快就会尝试重现一个最小的例子,看看它是如何进行的。抱歉,我是新来的,在这里提问。

c++ inheritance virtual-inheritance public-method
1个回答
-1
投票

您在

r
中有一个私有成员变量
HammachePotential
,它隐藏了
Potential
中的方法。确保检查编译器的完整错误消息,GCC 至少给出了足够的提示来解决这个问题: https://godbolt.org/z/bbv5v9feh

<source>:188:7: error: 'double HammachePotential::r' is private within this context
  188 |     a.r();
      |       ^
<source>:162:12: note: declared private here
  162 |     double r;
      |            ^
<source>:188:8: error: expression cannot be used as a function
  188 |     a.r();
      |     ~~~^~
© www.soinside.com 2019 - 2024. All rights reserved.