1
我想提供一个对象的一次性配置。C++ 11类的静态结构编译,为什么不链接?
此代码:
class Foo
{
public:
static struct Bar {
bool a = true;
int b = 69;
} bar;
};
int main(int argc, char **argv)
{
Foo::bar.a = false;
}
编译就好:
$ g++ -c -std=gnu++11 main.cpp
但链接器抱怨缺少符号:
$ g++ main.o
Undefined symbols for architecture x86_64:
"Foo::bar", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
为什么不这项工作?
and
什么是实现同样目标的更好方法?
啊!我认为支撑或平等初始化器会这样做。我会尽快接受...你打赌接受计时器。 – helpwithhaskell
@helpwithhaskell你只能初始化内部类的数据成员,而不能初始化静态类成员'bar'的数据成员。因此,任何代码如:'Foo :: Bar b;'都会将'b'的数据成员初始化为您提供的值,这将是变量'b'的定义,就像上面的'Foo :: Bar Foo :: bar'是Foo(静态成员)变量bar的定义。 – rubenvb