如何从静态方法改变C++中对象的属性

1 c++ static-methods

如何在C++中从静态方法更改对象属性?我的方法必须是静态的.

码:

class Wrapper
{
    private:
        double attribute; //attribute which I want to change
    public:
        Wrapper();
        ~Wrapper();
        static void method(double x);
}
Run Code Online (Sandbox Code Playgroud)

我试过了:

std::string Wrapper::method(double x)
{
    attribute = x;
}
Run Code Online (Sandbox Code Playgroud)

但:

error: invalid use of member ‘Wrapper::attribute’ in static member function
Run Code Online (Sandbox Code Playgroud)

Est*_*iny 6

也许这样:

std::string Wrapper::method(double x, Wrapper& obj)
{
    obj.attribute = x;
}
Run Code Online (Sandbox Code Playgroud)

但如果你有这样的问题,你应该重新考虑你的设计.引用类实例的方法没有共振是静态的.

静态方法不与类的任何实例相关联,而是与类本身相关联.编译器不知道,这个类只有一个实例.您的问题有许多可能的解决方案,但正确的解决方案取决于您希望以更大的规模实现的目标.