【发布时间】:2016-01-04 13:33:47
【问题描述】:
我现在对继承很困惑。我计划简单地覆盖变量的初始值。在下面的代码中,我只是继承了基类并尝试获取它的名称,该名称与类一起保存为字符串。我希望派生类可以覆盖这个值,但它没有这样做。
我的预期输出是
Derived
Derived
但是我得到了
Base
Base
以下实现的正确方法是什么?
#include <iostream>
#include <string>
struct Base {
virtual ~Base() = default;
virtual void id(){
std::cout << id_ << std::endl;
}
std::string id_ = "Base";
};
struct Derived : public Base {
virtual ~Derived() = default;
std::string id_ = "Derived";
};
int main(){
Base* b = new Derived();
Derived* d = new Derived();
b->id();
d->id();
delete d;
delete b;
return 0;
}
【问题讨论】:
-
成员变量不能是虚拟的(即可覆盖),只能是方法。
标签: c++ inheritance