如何在C ++中访问类变量 [英] How access class variables in c++

查看:92
本文介绍了如何在C ++中访问类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++中是否可以在不创建对象的情况下访问其他类中的类变量。我尝试使用静态,但另一个类无法识别我的变量。
我有3节课。其中两个应该使用sae变量。在第三堂课中,我正在更改值。如果您能提供帮助,将不胜感激。

Is it possible in c++ to access class variables in other classes without creating an object. I have tried to use static, but the other class doesnt recognize my variable. I have 3 classes. In two of those the sae variables should be used. In the third class I am changing the values. Would be grateful if you could help. Maybe youve got an example.

推荐答案

class Myclass
{

    public:
         static int i;
};

int Myclass::i = 10;


class YourClass
{

    public:
        void doSomething()
        {
             Myclass::i = 10;  //This is how you access static member variables
        }

};

int main()
{
    YourClass obj;
    obj.doSomething();
    return 0;
}

这篇关于如何在C ++中访问类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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