欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

C++里的花括号{},块,作用域

发布时间:2023/12/20 42 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C++里的花括号{},块,作用域 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
{ } 里的内容是一个“块”。
单独的{ }在执行顺序上没有改变,仍然是顺序执行,不同的是标识符的作用域限定 。


#include <iostream> #include <string> using namespace std;
class tcalss {     string Name; public:     tcalss(string name){Name=name;cout<<"build "<<Name<<endl;};     ~tcalss(){cout<<"kill "<<Name<<endl;}; };
int main() {
    int Test=100;     cout<<"out of {} Test ="<<Test<<endl;
    tcalss x("class out of {}");          {          tcalss y("class in {}");          float Test=3.14159;          cout<<"in {} Test= "<<Test<<endl;      }         cout<<"Out Of {} Test="<<Test<<endl; } 
====================================================================================================== 花括号可以看作是作用域标识符,除了在写函数时候用到,它还有一个作用就是表示变量的作用域: {int a=0;{int b=0;a=1; //正确,还在a的作用域中}b=1; //错误,因为不在b的作用域,b已经被销毁了 } ========================================================================================================== 参考:http://www.360doc.com/content/14/0417/11/11948835_369707933.shtml 在C/C++中大括号指明了变量的作用域,在大括号内声明的局部变量其作用域自变量声明开始,到大括号之后终结。 void MyProcess(MyType input, MyType &output) { MyType filter = input;
   {       MyType temp;       step1(filter,temp);    }
   {       MyType temp;       step2(filter,temp);    }
   {       MyType temp;       step3(filter,temp);    }    output = filter; }
以上程序实现了简单的管道/过滤器结构: temp1    temp2   temp3 |       |      | input --> step1 --> step2 --> step3 --> output temp都是临时变量,如果没有大括号的约束,每个临时变量都存在于函数作用域中,那么频繁增减流程时出错的概率大大增加。 放在大括号中,不仅程序阅读起来很清楚,而且也不容易出错

总结

以上是生活随笔为你收集整理的C++里的花括号{},块,作用域的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。