gpt4 book ai didi

c++ - 初始化静态成员使编译工作......但是为什么

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

我有 3 个文件:

main.cpp -

#include "test.hpp"

int main(void)
{
test x;
return (1);
}

测试.hpp-

#ifndef TEST_HPP
#define TEST_HPP

class test
{
static int a;

public:
void func(void);
};

#endif

测试.cpp-

#include "test.hpp"

int test::a = 0; // removing this line makes compilation fail

void test::func(void)
{
a--;
}

我用:clang++ *.cpp -I . 编译,我的目录中只有这 3 个文件。

编译失败信息是:

Undefined symbols for architecture x86_64:
"test::a", referenced from:
test::func() in test-8bbfc4.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

根据我的理解:

int   test::a = 0; // removing this line makes compilation fail

只是将静态成员 a 初始化为 0,因为它已经是 0 实际上没有任何意义。

为什么这会对编译产生影响?

最佳答案

was just initializing the static member a to 0

不,它不只是初始化,它是static data member 的定义.没有它,您将收到如您所见的链接错误。

The declaration inside the class body is not a definition...

顺便说一句:Constant static members *inline static members (C++17 起)可以在类定义中定义。


*请注意,当 const 非内联非 constexpr 静态数据成员被 ODR 使用时,仍然需要在命名空间范围内定义,但它不能有初始化器。

关于c++ - 初始化静态成员使编译工作......但是为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125651/

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