微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/c/114205.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐