简体   繁体   English

如何访问 c++ 中的 class 变量

[英]How access class variables in c++

Is it possible in c++ to access class variables in other classes without creating an object.是否可以在 c++ 中访问其他类中的 class 变量而无需创建 object。 I have tried to use static, but the other class doesnt recognize my variable.我曾尝试使用 static,但另一个 class 无法识别我的变量。 I have 3 classes.我有3节课。 In two of those the sae variables should be used.其中两个应该使用 sae 变量。 In the third class I am changing the values.在第三个 class 中,我正在更改值。 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;
}

static is 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 protected or private , thus rendering it inaccessible from other code.您将 class 变量设置为protectedprivate ,从而使其无法从其他代码访问。
  2. You forgot to specify the full scope of the class variable (with A:: in this example).您忘记指定 class 变量的完整 scope(在本例中为A:: :)。

I think the Singleton Pattern would help, but I'm no big fan of it.我认为Singleton 模式会有所帮助,但我不是它的忠实粉丝。 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.更好的设计是让一个 class 拥有 object,并将对该 object 的引用传递给其他类。

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;


              }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM