无法覆盖派生类中的静态初始化

lur*_*her 5 c++ inheritance static-initialization

我正在尝试为层次结构中的类提供不同的静态初始化,但是当我尝试使用此代码时:

#include <iostream>

using namespace std;

struct base {
static const char* componentName;
};
const char* base::componentName = "base";

struct derived : public base {};

const char* derived::componentName = "derived";

int main() {

cout << base::componentName << endl;
cout << derived::componentName << endl;
}
Run Code Online (Sandbox Code Playgroud)

我最终得到了这个构建错误:

test.cpp:15: error: ISO C++ does not permit ‘base::componentName’ to be defined as ‘derived::componentName’
test.cpp:15: error: redefinition of ‘const char* base::componentName’
test.cpp:11: error: ‘const char* base::componentName’ previously defined here
Run Code Online (Sandbox Code Playgroud)

似乎静态初始化不能在派生类上重写?如果这不起作用,我可能总是将componentName定义为一个返回const char*的静态函数,唯一的问题是我希望对部分特化进行初始化,并且似乎没有任何方法我知道在部分特化中只重新定义一个函数,而不复制将保持大部分相同的所有其他代码

Ebo*_*ike 6

您还需要在子类中声明它.

struct derived : public base {
    static const char* componentName;
};
Run Code Online (Sandbox Code Playgroud)