如何在本地范围内访问全局变量?

use*_*728 21 c++ global-variables local

这是我的代码

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

我得到输出1,但我想5,如访问全局x变量.

这可能吗?

Kod*_*Kid 33

您应该使用::x以便在本地范围内访问全局变量.操作员::是一元范围解析操作员.所以你的代码应该是:

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

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

  1. 二进制范围解析运算符.
  2. 一元范围分辨率算子.

几乎在整个编码时间内,您将使用二进制范围解析运算符.所以虽然这个问题的答案是一元范围解析算子; 为了便于将来参考,我列出了二进制范围解析运算符的一些典型用例.

二进制范围解析运算符的用例:

1.在课堂外定义你的功能.

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

例如,Car.h文件如下所示:

class Car
{
    private:
        int model;
        int price;

    public:
        void drive();
        void accelerate();
};
Run Code Online (Sandbox Code Playgroud)

Car.cpp看起来像:

void Car :: drive()
{
    // Driving logic.
}
void Car :: accelerate()
{
    // Logic for accelerating.
}
Run Code Online (Sandbox Code Playgroud)

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

  1. 班级名称
  2. 功能名称

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


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

请考虑以下代码:

#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.
}
Run Code Online (Sandbox Code Playgroud)

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


3.覆盖被覆盖的功能.

二进制作用域解析运算符有助于调用基类的函数,该函数使用派生类的对象在派生类中重写.请参阅以下代码:

#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.
}
Run Code Online (Sandbox Code Playgroud)

4.访问静态数据成员.

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为一元 `::` 和二进制 `::` 是一回事,只是全局作用域没有名称。 (4认同)