因此,我知道在C++中,如果静态成员是const文本类型,则可以在类中初始化它们,如下所示
class test{
public:
static constexpr int stc = 1;
private:
int a = 0;
int b = 0;
int c = 0;
};在编译器可以直接替换成员值的情况下,可以使用静态stc变量,例如
int main () {int array[test::stc];} 但是,如果在编译器不能直接替换值的上下文中使用:
int main() { const int &cs = test::stc; } 然后编译器(clang)生成一个错误。
c++ -std=c++11 -pedantic t.cpp -o t
Undefined symbols for architecture x86_64:
"test::stc", referenced from:
_main in t-a8ee2a.o
ld: symbol(s) not found for architecture x86_64除非静态成员在类的外部定义,如下所示:
constexpr int test::stc;
为什么是这种情况?
发布于 2018-05-01 05:43:27
在……里面
int main() { const int &cs = test::stc; } test::stc是odr-在
int main () {int array[test::stc];} 不是的。
来自C++11标准的以下示例支持上述思想。
结构S{ static x= 0;};const &f(const &r);int =b?(1,S:X) // S::x不是odr-在这里使用: f( S::x);// S-::x在这里使用,因此需要定义
从实际角度来看,cs将是一个无效的引用,除非test::stc有一个地址。另一方面,array只需要test::stc的值,它可以在编译时进行计算。array不需要test::stc的地址就能成为有效的对象。
odr使用的对象必须在程序中精确定义一次.
发布于 2018-05-01 00:17:35
static constexpr int stc = 1; // declares the static var
constexpr int test::stc; // defines the static var有关更详细的解释,请参阅下面的链接
http://www.learncpp.com/cpp-tutorial/811-static-member-variables/
发布于 2019-08-08 10:21:35
inline变量C++17
在C++17中,如果您也将静态成员标记为inline,那么我相信您可以自由地使用它,或者跨编译单元具有多个定义,例如:
#include <iostream>
class MyClass {
public:
inline static constexpr int i = 42;
};
int main() {
const int &cs = MyClass::i;
std::cout << cs << std::endl;
std::cout << &MyClass::i << std::endl;
}更多信息请访问:内联变量是如何工作的?
https://stackoverflow.com/questions/50109036
复制相似问题