假设您想复制以下Python代码段:
class Base:
name = "base"
def announce(self):
print(self.name)
class Derived(Base):
name = "derived"
Base().announce()
Derived().announce()
...将输出:
"base"
"derived"
最初,您可能倾向于编写如下内容:
#include <iostream>
#include <string>
struct Base {
std::string name = "base";
void announce() {
std::cout << name << std::endl;
}
};
struct Derived : public Base {
std::string name = "movie";
};
int main() {
Base().announce();
Derived().announce();
return 0;
}
但是这里Derived.name
只是阴影Base.name
。调用Derived.announce()
引用Base.name
并打印“ base”。
有什么办法可以实现这种行为?如果可能的话,最好没有类模板。
C ++的工作方式不像Python(这并不奇怪,毕竟它们是两种非常不同的语言),并且在继承的类中定义的成员变量实际上定义了一个与父类的变量无关的新变量。
一种可能的解决方案是创建第二个(可能受保护的)Base
构造函数,该构造函数将name
用作参数,然后Derived
类可以使用它来初始化成员:
struct Base {
Base() = default; // A defaulted default constructor
std::string name = "base";
void announce() {
std::cout << name << std::endl;
}
protected:
explicit Base(std::string name)
: name{ std::move(name) } // Initialize the member
{
}
};
struct Derived : public Base {
Derived()
: Base("movie") // Initialize the base class using the special constructor
{
}
};
Base
需要默认的默认构造函数,因为如果您声明另一个构造函数,则编译器不会自动为您生成默认构造函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句