如何访问c ++中的特定范围? [英] how to access a specific scope in c++?

查看:210
本文介绍了如何访问c ++中的特定范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;
int x=24 ;
int main()
{
     int x=0;
     {
         int x=5 ;
        ::x= x+2 ;
     }
    cout<<::x<<endl  ;//first 
    cout<<x<<endl ; // second 
    return 0;
} 

在这个简单的例子中,我使用代码块,我知道我可以修改全局变量使用Scope解析运算符。
和我修改全局变量在这个例子,但我想知道是否有一种方法来修改特定范围内的变量,如main函数(不必要的(Scope resolution operator)方式)
意思是在这个例如我需要第一个输出是24和下一个7。
对我的英语抱歉我希望理解这个问题

in this simple example i'm using code block and i know i can modify the global variables using Scope resolution operator. and i modify the global variable in this example but i wonder if there is a way to modify the variables in specific scope like main function (not necessary the( Scope resolution operator) way ) that mean in this example i need the first output is 24 and the next one 7 . sorry for my english i hope to understand the question

推荐答案

C ++的范围规则是文本和AFAIK这样做,因为你不能把命名空间放在函数内部。但是引入一个具有唯一名称的引用可能会帮助你作为解决方法,如果你发现自己在这样的绑定:

The scoping rules of C++ are textual and AFAIK you can't do this, as you can't go putting namespaces inside of functions. But introducing a reference with a unique name may help you as a workaround if you find yourself in a bind like this:

#include <iostream>
using namespace std;
int x = 24;
int main()
{
     int x = 0;
     int & main_outer_x = x;
     {
         int x = 5;
         main_outer_x = x + 2;
     }
    cout << ::x << endl; //first 
    cout << x << endl; // second 
    return 0;
}

这会给你:

24
7

在生成的代码中再花费更多的内存,并允许保持外部名称不变。但是,如果你有意在一个函数中有一个名称冲突,可能会混淆和容易出错。这是抽象代码,所以很难批评,但最具体的代码与这样的模式应该是另一种方式。

That shouldn't cost any more memory in your generated code, and lets you keep the outer name untouched. Still, likely to be confusing and error prone if you're purposefully having a name collision within a function. This is abstract code so it's hard to criticize, but most concrete code with such a pattern should probably be done another way.

这篇关于如何访问c ++中的特定范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆