Sta*_*tan 8 c++ oop static class
我的函数是静态的非常重要,我需要访问和修改另一个静态/非静态类成员,以便以后打印出来.我怎样才能做到这一点?
#include <iostream>
class MyClass
{
public:
static int s;
static void set()
{
MyClass::s = 5;
}
int get()
{
return MyClass::s;
}
MyClass()
{
this->set();
}
};
void main()
{
auto a = new MyClass();
a->set(); // Error
std::cout << a->get() << std::endl; // Error
system("pause");
}
Run Code Online (Sandbox Code Playgroud)
LNK2001: unresolved external symbol "public: static int MyClass::s" (?s@MyClass@@2HA)
LNK1120: 1 unresolved externals
Run Code Online (Sandbox Code Playgroud)
Dre*_*ann 12
您已声明了静态变量,但尚未定义它.
创建和销毁包含对象时,将创建和销毁非静态成员变量.
但是,静态成员需要独立于对象创建而创建.
添加此代码以创建int MyClass::s:
int MyClass::s;
Run Code Online (Sandbox Code Playgroud)
附录:
C++ 17添加了内联变量,允许您使用较小的更改进行编码:
static inline int s; // You can also assign it an initial value here
^^^^^^
Run Code Online (Sandbox Code Playgroud)