问题
How to change object attribute from static method in C++? My method must be static.
Code:
class Wrapper
{
private:
double attribute; //attribute which I want to change
public:
Wrapper();
~Wrapper();
static void method(double x);
}
I tried:
std::string Wrapper::method(double x)
{
attribute = x;
}
But:
error: invalid use of member ‘Wrapper::attribute’ in static member function
回答1:
A static member function cannot access a non-static member because there is no object whose member you'd be referring to. Sure, you could pass a reference to an object as a parameter as suggested, but that's just silly because you might just as well make the function a non-static member.
It is a kind of object which is and will be created only once.
The simplest solution is to make the member static
. static
members can be accessed without an object because static
members are shared for all instances.
tried to make attribute static, but I got error: undefined reference to `Wrapper::attribute
That means you forgot to define the variable.
回答2:
Maybe this way:
std::string Wrapper::method(double x, Wrapper& obj)
{
obj.attribute = x;
}
But if you have such a problem, you should rethink your design. Methods referring to instance of a class have no reson to be static.
Static methods are not associated with any instance of the class but with the class itself. Compiler has no idea, that there is only one instance of this class. There are many possible solutions for your problem, but the correct one depends on what you want to achieve in a bigger scale.
回答3:
method
is a class method and attribute
is an instance variable. There is no instance and therefore no attribute
when method
is called in your current design. The only way to change an instance variable (like attribute
) is to provide an instance of Wrapper
to method
. There are several possible solutions. Some ideas:
- an instance as a parameter to
method
(see Estiny's answer) - a global instance of
Wrapper
(not advised) - make
Wrapper
a singleton (in general not advised, but singletons can be a solutions in some situations)
来源:https://stackoverflow.com/questions/32478983/how-to-change-attribute-of-object-in-c-from-static-method