对静态变量c++的未定义引用
Undefined reference to static variable c++
嗨,我在下面的代码中得到未定义的引用错误:
class Helloworld{
public:
static int x;
void foo();
};
void Helloworld::foo(){
Helloworld::x = 10;
};
我不想要一个static
foo()
函数。如何在类的非static
方法中访问类的static
变量?
我不想要
static
foo()
函数
好吧,foo()
在你的类中是不是静态的,你不不需要使它成为static
以便访问你的类的static
变量。
class Helloworld {
public:
static int x;
void foo();
};
int Helloworld::x = 0; // Or whatever is the most appropriate value
// for initializing x. Notice, that the
// initializer is not required: if absent,
// x will be zero-initialized.
void Helloworld::foo() {
Helloworld::x = 10;
};
代码是正确的,但不完整。类Helloworld
有一个静态数据成员x
的声明,但是没有定义。在源代码中需要
int Helloworld::x;
或者,如果0不是合适的初始值,则添加初始化器
老问题,但是;
由于c++17
,你可以声明static
成员inline
并在class
的体中实例化它们,而不需要out-of-class
定义:
class Helloworld{
public:
inline static int x = 10;
void foo();
};
相关文章:
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 对 Scalar ::Scalar() 的未定义引用
- 对复制 CTOR 和 CTOR 的未定义引用
- 对显式实例化的模板函数的未定义引用
- TensorRT (C++ API) 对"createNvOnnxParser_INTERNAL"的未定义引用
- 2个模板化类的非模板友元函数未定义引用错误
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 获取对function_name的未定义引用
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- 对结构方法的未定义引用
- 使用内联函数 c++ 的未定义引用
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 对 DLOPEN 的未定义引用
- QT C++中对全局变量的未定义引用
- 快速数学导致对"__pow_finite"的未定义引用
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用