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 BMWn"; } }; 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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- reactor-core – java.lang.IllegalStateException:队列已
- nand flash坏块管理OOB,BBT,ECC
- postgresql – Postgres使用JSONB INSERT ON CONFLICT
- dart – Flutter:设置AppBar的高度
- ruby-on-rails – Rails / Postgresql SQL差异w /日期
- .net – 类中有多少对象太多了?
- 单元测试 – 使用Mocha和Enzyme测试使用React CSS模块的Rea
- 计算NandFlash要传入的行地址和列地址
- xml--通过DOM解析XML
- Nand Flash,Nor Flash,CFI Flash,SPI Flash 之间的关系