It is very important that my function is static, I need to access and modify another static/non-static class member in order to print it out later. How can I do that?
#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");
}
LNK2001: unresolved external symbol "public: static int MyClass::s" (?s@MyClass@@2HA)
LNK1120: 1 unresolved externals
You have declared your static variable, but you have not defined it.
Non-static member variables are created and destroyed as the containing object is created and destroyed.
Static members, however, need to be created independently of object creation.
Add this code to create the int MyClass::s
:
int MyClass::s;
Addendum:
C++17 adds inline variables, allowing you code to work with a smaller change:
static inline int s; // You can also assign it an initial value here
^^^^^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With