c – 如何访问本地范围内的全局变量?

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

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

这可能吗?

解决方法

您应该使用:: x来访问本地范围内的全局变量.运算符::是一维范围解析运算符.所以你的代码应该是:
#include <iostream>
   using namespace std;
   int x = 5;
   int main()
   {
       int x = 1;
       cout << "The variable x: " << ::x << endl;
   }

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

>二进制范围解析运算符.
>一般范围分辨率运算符.

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

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

在课外定义你的功能.

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

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

class Car
{
    private:
        int model;
        int price;

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

Car.cpp看起来像:

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

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

>类名
>函数名称

因此,它实质上定义了函数的范围,即它通知编译器函数drive()属于类Car.

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

由于BMW类的派生功能具有相同的模板,所以调用b.drive将导致编译错误.因此,要指定我们想要的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.
}

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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...