如何从静态方法更改C++中对象的属性 [英] How to change attribute of object in C++ from static method

查看:42
本文介绍了如何从静态方法更改C++中对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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.

它是一种只会被创建一次的对象.

It is a kind of object which is and will be created only once.

最简单的解决方案是使成员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 的引用

tried to make attribute static, but I got error: undefined reference to `Wrapper::attribute

这意味着您忘记定义变量.

That means you forgot to define the variable.

这篇关于如何从静态方法更改C++中对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆