问题描述
如何在 C++ 中从静态方法更改对象属性?我的方法必须是静态的.
How to change object attribute from static method in C++? My method must be static.
代码:
class Wrapper
{
private:
double attribute; //attribute which I want to change
public:
Wrapper();
~Wrapper();
static void method(double x);
}
我试过了:
std::string Wrapper::method(double x)
{
attribute = x;
}
但是:
error: invalid use of member ‘Wrapper::attribute’ in static member function
推荐答案
静态成员函数无法访问非静态成员,因为没有您要引用其成员的对象.当然,您可以按照建议将对象的引用作为参数传递,但这很愚蠢,因为您也可以将函数设为非静态成员.
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.
它是一种只会被创建一次的对象.
最简单的解决方案是使成员static
.static
成员可以在没有对象的情况下访问,因为 static
成员为所有实例共享.
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.
试图将属性设为静态,但出现错误:未定义对 `Wrapper::attribute 的引用
这意味着您忘记定义变量.
That means you forgot to define the variable.
这篇关于如何从静态方法更改C++中对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!