gpt4 book ai didi

c++ - 是否应该在 C++ 头文件中初始化 const 静态变量?

转载 作者:可可西里 更新时间:2023-11-01 18:37:06 28 4
gpt4 key购买 nike

我的测试.h

#ifndef MY_TEST  
#define MY_TEST

struct obj {
int x;
int y;
};

class A {
private:
const static int a=100;
const static obj b;
};

const obj A::b={1,2};

#endif

当使用这个头文件编译cpp时,出现错误'multiple definition of 'A::b'

  1. 为什么我已经在使用保护宏了?
  2. 为什么 A::a 不产生错误? (我不能在 class A 中编写代码 const static obj b={1,2})

最佳答案

why is this when I have been using guard macro already?

header 保护仅防止在同一个 中多次包含 header 文件内容translation unit 不跨多个翻译单元。

why is A::a does not have the error message (I can't write code const static obj b={1,2} in class A)

In-class initialization编译器允许将 作为 const 文字类型的静态数据成员的特例。您的示例是类内初始化。

const A::b 在包含 header 的每个翻译单元中定义相同的符号名称,因此打破了 one definition rule

您需要将定义移动到一个且仅一个源 cpp 文件,以便它只定义一次。

关于c++ - 是否应该在 C++ 头文件中初始化 const 静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15020328/

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