How to declare a global variable that could be used in the entire program

后端 未结 9 1037
别那么骄傲
别那么骄傲 2020-12-13 14:52

I have a variable that I would like to use in all my classes without needing to pass it to the class constructor every time I would like to use it. How would I accomplish th

9条回答
  •  庸人自扰
    2020-12-13 15:31

    The below solution should be simple enough as per the title "How to declare a global variable that could be used in the entire program " . If you want to use it in a different file then make use of extern keyword.

    Please let me know if there is any issue with the solution

    #include
    
    using namespace std;
    
    int global = 5;
    
    class base {
        public:
            int a;
            float b;
            base (int x) {
                a = global;
                cout << "base class value =" << a << endl;
            }
    };
    
    class derived : public base {
        public:
            int c;
            float d;
            derived (float x, int y) : base (y)
            {
                d = global;
                cout << "derived class value =" << d << endl;
            }
    };
    
    
    int main ()
    {
        derived d(0,0);
        cout << "main finished" << endl;
        return 0;
    }
    

提交回复
热议问题