初始化依赖于子类的继承类的常量类成员
Initialize constant class member of inherited class depended of subclass
假设我有一个这样的模板基类:
class Util {
public:
Util(const std::string& suffix) : name(base_name + "." + suffix) {}
protected:
const std::string base_name = "Util";
const std::string name;
};
我想创建许多具有不同名称的子类。
我可以这样做:
class WorkingUtil : public Util {
public:
WorkingUtil() : Util("Working") {}
};
但不是这样的:
class Bad1Util : public Util {
public:
Bad1Util() : Util(suffix) {}
private:
const std::string suffix = "Bad1";
};
也不是这个:
class Bad2Util : public Util {
public:
Bad2Util() : suffix("Bad2"), Util(suffix) {}
private:
const std::string suffix;
};
这是一个 godbolt 示例和错误:
在抛出 'std::bad_alloc'what
(( 的实例后调用终止::bad_alloc
这里到底有什么问题?我可以像上面的例子一样做,但我想知道为什么其他的例子是不可接受的。
使用-Wextra
和-Wall
编译代码;
<source>:49:9: warning: field 'suffix' will be initialized after base 'Util' [-Wreorder-ctor]
suffix("Bad2"),
如果一个名字是你想要的:
以编程方式获取派生类的名称
实际上,有一个 int 可能会更好,所以你可以打开它,这可能是最简单的,使用一个简单的覆盖方法,如 public:int getClassID(({ return constant_# ; },所以每个类只有一个 #,而不是实例变量。 编译器可以内联它,因此它具有变量的效果。
相关文章:
- 私有类型的静态常量成员
- constexpr构造函数需要常量成员函数时出现问题
- Clang 格式 10.0 与 5.0 常量成员函数的格式不同
- 为什么"具有常量成员的结构"类型的指针不能指向"具有非常量成员的结构"?
- 常量成员函数中成员变量的类型
- 如何处理运算符=中的常量成员?
- 常量成员和没有setter的私有成员之间有什么区别
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 移动具有常量成员的类的构造和分配
- ARM C++编译器不会编译具有可变常量成员的结构
- 强制在编译时计算类的类的常量成员
- 类中常量成员函数的 c++ 链接错误
- 为什么常量成员可以初始化两次?
- 专用常量成员函数的成员检测
- 与其他静态const成员初始化静态常量成员
- 具有静态和常量成员变量的对象
- 结构中的常量成员即使在初始化后也返回 0
- 在非常量成员函数中,为什么点这个非常量,而 decltype 指针这是常量
- 有没有一种通用方法来"unprotect"静态常量成员?
- 如何初始化共享复杂初始化代码的多个常量成员变量?