如何初始化子类中的静态常量成员变量?
我正在尝试制作一个模板,它可以制作几种不同类型的类,这些类主要在名称上有所不同,即电阻器应输出“电阻:4 欧姆”,而电容器应输出“电容:4 法拉”相同的函数调用,没有重载。理想情况下,单位只是 static const std::string 值。
我的方法是使用未初始化的基类,
这里的问题是现在我必须在所有子类中重载所有不同类型的构造函数。
有没有办法只初始化子类中的静态常量变量?
谢谢
I'm trying to make a template which can make a few different types of classes that differ mainly in the name of things, i.e. a resistor should output "Resistance: 4 ohm" where a capacitor would output "Capacitance: 4 farad" in the same function call, without overloading. Ideally the units would just be static const std::string values.
My method was to make the base class with uninitialized
Problem here is that now I have to overload all my different types of constructors in all the subclasses.
Is there a way to just initialize the static const variables in the subclass?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当前标准不允许在派生类构造函数中初始化基类的
public/protected
成员。必须依靠其他技术才能实现这一目标。有两种方法可以解决您的问题。(1) 声明
virtual
方法返回std::string
以获得适当的标签/值。然而,这会带来不必要的开销。从你的实现中我可以看出你想避免它。(2) 使用中间
template
类,它将为您完成此操作。Initializing
public/protected
members of base class inside a derived class constructor is not allowed by current standard. One has to rely on other techniques to achieve it. There are 2 ways to address your problem.(1) Declare
virtual
method returningstd::string
for appropriate label/values. However, this will cause unnecessary overhead. From your implementation I can make out that you want to avoid it.(2) Use an intermediate
template
class, which will do it for you.CRTP 可能会有所帮助:
CRTP might be helpful:
我猜取决于你的要求:
输出:
Depends on your requirements i guess:
output: