以下代码生成对“Test::color”的 undefined reference
。
#include <iostream>
struct Color{
int r,g,b;
};
void printColor(Color color) {
//printing color
}
class Test {
static constexpr Color color = {242,34,4};
public:
void print(){
printColor(color);
}
};
int main() {
Test test;
test.print();
return 0;
}
考虑到我想使用最新版本的标准 C++17,为什么此代码会产生上述错误?避免该错误的最佳方法是什么?
我应该定义静态成员变量,就像标准早期修订版中需要的那样(请参阅此处的第一个答案: Undefined reference to static constexpr char[] ),还是应该创建一个新的 Color
结构作为可以在下面看到吗?
printColor(Color{color.r, color.g, color.b});
编辑:
我在 Ubuntu 16.04 上使用 CLion,据我所知,它使用 g++ 5.4 进行编译。我已将其设置为使用 C++17,但仍然出现相同的错误。仅当将 color
传递给函数时才会出现该错误。
最佳答案
这是因为,在 C++17 之前,您必须在类外部专门定义静态变量:
class Test {
/* ... etc etc ... */
}
const constexpr Color Test::color;
静态成员的常量表达式不允许您“放弃”此显式定义要求。
使用 C++17,您不再需要显式定义静态成员。它们是隐式的“内联”变量,在某个时刻自动定义,并且每个二进制文件仅定义一次,而无需您处理它。请参阅here对于此功能的长提案。
请注意,定义只能出现在单个翻译单元中(因此可能不会出现在包含大量 Test 类的 header 中)。
关于c++ - 为什么不能将 static constexpr 成员变量传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52355223/