• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C++示范在不同的范围内不冲突使用同名变量的范例

OC/C/C++ 水墨上仙 2137次浏览

C++演示在不同的范围内不冲突使用同名变量的范例

// An example of using the same variable declarations in different scopes in C++ without conflicts
 
#include <iostream>
 
using std::cout;
using std::endl;
 
class abc  //Class declaration statement, you can use struct, and union also.
{
    public:
    int x;  //Variable declaration within class.
    abc():x(10){}  //Constructor to intialize data members.
};
 
namespace def  //Namespace declaration statement.
{
    int x = 20;//Variable declaration within def space.
}
 
int getx()  //Function return its local variable.
{
    int x = 30;   //Variable declaration within function space.
    return x;
}
 
int x = 40;   //Global space variable declaration.
 
int main()
{
    int x = 50;//Local space variable declaration within main function.
    abc a;
 
    cout << "Scope within class abc:  x = " << a.x
         << "\nScope within namespace def:  x = " << def::x
         << "\nScope within function getx:  x = " << getx()
         << "\nScope within global scope :  x = " << ::x
         << "\nScope within local main function:  x = " << x;
 
         {
             int x = 60;  //Local scope variable declaration within segment of code
             cout << "\nScope within local code block:  x = " << x;
         }
         cout<<endl<<endl;//Send two new line to the screen
 
    return 0;
}
 
/*Program Output:
Scope within class abc:  x = 10
Scope within namespace def:  x = 20
Scope within function getx:  x = 30
Scope within global scope :  x = 40
Scope within local main function:  x = 50
Scope within local code block:  x = 60
*/


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C++示范在不同的范围内不冲突使用同名变量的范例
喜欢 (0)
加载中……