C++ 如何在局部范围内访问全局变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20458720/
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-27 23:09:36  来源:igfitidea点击:

How to access a global variable within a local scope?

c++global-variableslocal

提问by user3080728

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 xvariable.

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

Is this possible?

这可能吗?

回答by KodingKid

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

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

   #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++:

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

  1. Binary scope resolution operator.
  2. Unary Scope resolution operator.
  1. 二进制范围解析运算符。
  2. 一元范围解析运算符。

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.

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

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

我们将代码组织成扩展名为.h 的头文件和扩展名为.cpp 的代码文件。在代码文件中定义函数时,我们使用::二进制范围解析运算符。

For example,a Car.hfile looks like:

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

class Car
{
    private:
        int model;
        int price;

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

And Car.cppwould look like:

Car.cpp会是什么样子:

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
  1. 班级名称
  2. 函数名

Hence, it essentially defines the scope of the function i.e. it informs the compiler that the function drive()belongsto the classCar.

因此,它本质上定义了功能的范围,即它通知函数,编译器驱动器()所属车辆。



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

2. 解决派生自不同类的具有相同模板的两个函数之间的歧义。

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.drivewill result into a compilation error. Hence, to specify which drive()we want, we use the ::operator.

由于类 BMW 的两个派生函数具有相同的模板,调用b.drive将导致编译错误。因此,要指定我们想要哪个drive(),我们使用::运算符。



3. To override the overridden function.

3. 覆盖被覆盖的功能。

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.

4. 访问静态数据成员。

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