类继承的C++问题
我有一些变量和函数的基类以及多个子类。我想尽可能减少子类中所需的代码量。
我的代码示例:
#include <iostream>
class base{
public:
int a = 10;
int b;
void print()
{
std::cout << a <<std::endl;
}
};
class child: public base
{
public:
int a;
};
int main()
{
child ch;
ch.a = 20;
ch.print();
}
由于打印了结果编号 10,这意味着使用了基类变量a,但我需要使用子类变量(如果存在)。所以这个例子的预期输出是 20。
回答
在子类中覆盖基类中的变量是一个重大错误。这会非常惊人地反咬你。
发生的事情是 ch.a 来自子类(被覆盖的版本),但打印函数是基类的一部分,因此它将打印该版本。
如果有某种原因要这样做(我想不出一个原因),那么您可以在分配之前将 ch 类型转换为基类。像这样的东西:
(static_cast<base>(ch)).a = 20;
但更好的选择是永远不要重载变量名。
- @JosephLarson It can be a “good idea” purely because they are distinct scopes, and what I’m doing in `child` shouldn’t be influenced by implementation details of `base`. I’ve got an (admittedly, special) case where I’m inheriting from a class and I need to store a member which is best described as `path`. That’s the perfect name for the member in this context. Alas, the base class *also* has a member of that name. But … who cares? These two members never cross paths. In fact, the base class member is `private` and the only reason I even know of it is by pure chance.