我有一个简单的类
class Foo {
public:
float m;
Foo();
}
Foo::Foo(){
this->m = 1.0f;
}
然后我用
扩展它class Bar: public Foo {
public:
float m;
Bar()
}
Bar::Bar(){
this->m = 10.0f;
}
然后我实例化 Bar()
但 Bar.m
仍然是 1.0f。这是有原因的吗?
最佳答案
在 C++ 中,您不能覆盖字段。只有方法可以被覆盖。因此,您在 Bar
类中声明的变量 m
是一个新字段,它隐藏了基类 Foo
的 版本米
。
如果你想从Bar
访问Foo
的m
,那么你可以使用这个语法:
Bar::Bar(){
this->Foo::m = 10.0f;
}
它明确告诉编译器写入 Foo
的 m
版本。或者,您可以删除 this->
并只写
Bar::Bar(){
Foo::m = 10.0f;
}
希望这对您有所帮助!
关于c++ - 从父类继承时覆盖变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8874345/