提问者:小点点

初始化继承类的依赖于子类的常量类成员


假设我有一个模板基类,如下所示:

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;
};

下面是一个天方夜谭的例子和错误:

引发“std::bad_alloc”的实例后调用的terminate
what():std::bad_alloc

这里的问题到底出在哪里? 我可以像上面的例子那样做,但是我想知道为什么其他的例子是不能接受的。


共2个答案

匿名用户

如果只需要一个名称:

以编程方式获取派生类的名称

实际上,有一个int可能更好,这样您就可以打开它,使用public:int getClassID(){return constant#;}这样的简单重写方法可能最容易,因此每个类只有一个#,而不是一个实例变量。 编译器可以将其内联,因此它具有变量的效果。

匿名用户

使用-wextra-wall编译代码;

<source>:49:9: warning: field 'suffix' will be initialized after base 'Util' [-Wreorder-ctor]

        suffix("Bad2"),