gpt4 book ai didi

c++ - 不能覆盖派生类中的静态初始化

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:53 25 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

你也需要在你的子类中声明它。

struct derived : public base {
static const char* componentName;
};

关于c++ - 不能覆盖派生类中的静态初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4241946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com