C++中如何访问类变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7077903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:26:44  来源:igfitidea点击:

How access class variables in c++

c++classvariables

提问by buddy

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.

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

采纳答案by Alok Save

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;
}

回答by Frerich Raabe

staticis the right keyword here:

static是正确的关键字:

class A {
public:
  static int i; // <-- this is a class variable
};

class B {
public:
  void f() { A::i = 3; } // <-- this is how you access class variables
};

They only potential problem I can think of is that

他们唯一我能想到的潜在问题是

  1. You made the class variable protectedor private, thus rendering it inaccessible from other code.
  2. You forgot to specify the full scope of the class variable (with A::in this example).
  1. 您使类变量protectedor private,从而使其无法从其他代码访问。
  2. 您忘记指定类变量的完整范围(A::在本例中为)。

回答by DanDan

I think the Singleton Patternwould help, but I'm no big fan of it. A lot better design would be to have one class take ownership of the object, and pass references to this object to the other classes.

我认为单例模式会有所帮助,但我不是它的忠实粉丝。更好的设计是让一个类获得对象的所有权,并将对该对象的引用传递给其他类。

回答by Kriss Sachintha

yes you can bro, try this

是的,你可以,兄弟,试试这个

struct car{

结构车{

        string model;
        string paint;
        int price;


           };


         int main(){

          // creates an object of the class car

            car BMW;

          // assign the values
           bmw.model = "m sports";
            bmw.paint ="red";
            bmw.price = 24000;


              }