如何访问本地范围内的全局变量? [英] How to access a global variable within a local scope?

查看:148
本文介绍了如何访问本地范围内的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

  #include< iostream> 
使用namespace std;
int x = 5;
int main()
{
int x = 1;
cout<< 变量x:<< x<< ENDL;
}

我得到输出 1 ,但我想要 5 ,就像访问全局 x 变量一样。



这可能吗?

解决方案

您应该使用: :x 以访问本地作用域中的全局变量。运算符 :: 是一元作用域解析运算符。所以你的代码应该是:

  #include< iostream> 
使用namespace std;
int x = 5;
int main()
{
int x = 1;
cout<< 变量x:<< :: x<< ENDL;
}

注意: :: 运算符在C ++中有两个含义:


  1. 二元作用域解析运算符。
  2. 一元作用域解析运算符。

几乎在整个编码时间内,您都将使用Binary范围解析运算符。所以虽然这个问题的答案是一元范围解析算子,只是为了将来的参考,我列举了Binary作用域解析运算符的一些典型用例。

Binary作用域解析运算符的用例:



1。在类之外定义你的函数。



我们用 .h 扩展名和代码文件将代码组织到头文件中, em> .cpp 扩展名。在代码文件中定义函数时,我们使用 :: 二进制作用域解析运算符。



例如,一个 Car.h 文件看起来像:

  class Car 
{
private:
int model;
诠释价格;

public:
void drive();
void accelerate();
};

Car.cpp 看起来像:

  void Car :: drive()
{
//驱动逻辑。
}
void Car :: accele()
{
//逻辑加速。



$ b $ p
$ b

在这里,我们可以很容易地注意到, :: 作用于两个操作数:


  1. 类名

  2. 函数因此,它本质上定义了函数的范围,即它通知编译器函数 drive()
  3. $ b

    2。解决具有相同模板的两个函数之间的歧义,这些模板来自不同的类。



    请考虑以下代码:

      #include< iostream> 
    使用namespace std;
    class Vehicle
    {
    public:
    void drive()
    {
    cout<< 我驾驶汽车。
    }
    };
    class Car
    {
    public:
    void drive()
    {
    cout<< 我正在开车。
    }
    };
    类宝马:公共汽车,公共车辆
    {
    //宝马特定功能。
    };
    int main(int arc,char ** argv)
    {
    BMW b;
    b.drive(); //这会导致编译错误,因为调用不明确。
    b.Car::drive(); //将调用Car的驱动方法。
    b.Vehicle :: drive(); //将调用车辆的驱动方法。





    $ b由于宝马级别的派生函数具有相同的模板, b.drive 会导致编译错误。因此,我们使用 :: 运算符来指定我们需要哪个 drive()





    3。二进制作用域解析运算符有助于调用派生类中使用派生类的对象覆盖的基类的函数。 。请参阅下面的代码:

      #include< iostream> 
    使用namespace std;
    class Car
    {
    public:
    void drive()
    {
    cout<< 我正在开车。
    }
    };
    class宝马:公共汽车
    {
    public:
    void drive()
    {
    cout<< 我正在驾驶宝马\ n;
    }
    };
    int main(int argc,char ** argv)
    {
    BMW b;
    b.drive(); //将调用宝马的驱动功能。
    b.Car::drive(); //将调用汽车的驱动功能。
    }






    4。访问静态数据成员。



    据我们所知,静态数据成员是由该类的对象按类别共享的。因此,我们不应该(尽管我们可以)使用对象来确定静态变量的范围。请参阅以下代码:

      #include< iostream> 
    使用namespace std;
    class Car
    {
    public:
    static int car_variable;
    };
    int Car :: car_variable;
    int main(int argc,char ** argv)
    {
    Car :: car_variable = 10;
    cout<< 汽车变量:<< Car :: car_variable<< \\\
    ;
    返回0;
    }


    This is my code

    #include <iostream>
    using namespace std;
    int x = 5;
    int main()
    {
        int x = 1;
        cout << "The variable x: " << x << endl;
    }   
    

    I get as output 1, but I would like to have 5, as in accessing the global x variable.

    Is this possible?

    解决方案

    You should be using ::x in order to access global variable in local scope. The operator :: is unary scope resolution operator. So your code should be:

       #include <iostream>
       using namespace std;
       int x = 5;
       int main()
       {
           int x = 1;
           cout << "The variable x: " << ::x << endl;
       }   
    

    Note: :: operator has two meanings in C++:

    1. Binary scope resolution operator.
    2. Unary Scope resolution operator.

    Almost for your entire coding hours, you would be using the Binary scope resolution operator. So although the answer to this question is unary scope resolution operator; just for the sake of future reference, I enlist some typical use cases of the Binary scope resolution operator.

    Use cases of the Binary scope resolution operator:

    1. To define your functions outside the class.

    We organize our code into header files with .h extension and code files with .cpp extension. While defining our functions in the code files, we use the :: Binary scope resolution operator.

    For example,a Car.h file looks like:

    class Car
    {
        private:
            int model;
            int price;
    
        public:
            void drive();
            void accelerate();
    };
    

    And Car.cpp would look like:

    void Car :: drive()
    {
        // Driving logic.
    }
    void Car :: accelerate()
    {
        // Logic for accelerating.
    }
    

    Here, as we can easily notice, :: acts on two operands:

    1. The class name
    2. The function name

    Hence, it essentially defines the scope of the function i.e. it informs the compiler that the function drive() belongs to the class Car.


    2. To resolve ambiguity between two functions with same template which are derived from different classes.

    Consider the following code:

    #include <iostream>
    using namespace std;
    class Vehicle
    {
        public:
        void drive()
        {
            cout << "I am driving a Vehicle.\n";
        }
    };
    class Car
    {
        public:
        void drive()
        {
            cout << "I am driving a Car.\n";
        }
    };
    class BMW : public Car, public Vehicle
    {
        // BMW specific functions.
    };
    int main(int arc, char **argv)
    {
        BMW b;
        b.drive();  // This will give compile error as the call is ambiguous.
        b.Car::drive();  // Will call Car's drive method.  
        b.Vehicle::drive();  // Will call Vehicle's drive method.
    }
    

    As both the derived functions of the class BMW have the same template, the call b.drive will result into a compilation error. Hence, to specify which drive() we want, we use the :: operator.


    3. To override the overridden function.

    Binary scope resolution operator helps to call the function of the base class which is overridden in a derived class using the derived class's object. See the code below:

    #include <iostream>
    using namespace std;
    class Car
    {
        public:
        void drive()
        {
            cout << "I am driving Car.\n";
        }
    };
    class BMW : public Car
    {
        public:
        void drive()
        {
            cout << "I am driving BMW\n";
        }
    };
    int main(int argc, char** argv)
    {
        BMW b;
        b.drive(); // Will call BMW's drive function.
        b.Car::drive(); // Will call Car's drive function.
    }
    


    4. To access static data members.

    As we know, static data members are shared per class basis by the objects of that class. Hence, we should not (although we can) use objects to scope the static variables. See the following code:

    #include <iostream>
    using namespace std;
    class Car
    {
        public:
        static int car_variable;
    };
    int Car :: car_variable;
    int main(int argc, char** argv)
    {
        Car :: car_variable = 10;
        cout << "Car variable: " << Car :: car_variable << '\n';
        return 0;
    }
    

    这篇关于如何访问本地范围内的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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