码迷,mamicode.com
首页 > 编程语言 > 详细

[C++] 用Xcode来写C++程序[6] Name visibility

时间:2015-03-09 23:43:06      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:

用Xcode来写C++程序[6] Name visibility

技术分享

 

此小结包括了命名空间的一些使用细节

 

命名空间

#include <iostream>
using namespace std;

namespace foo {
    // 函数
    int value() {
        return 5;
    }
}

namespace bar {
    // 常量
    const double pi = 3.1416;
    
    // 函数
    double value() {
        return 2*pi;
    }
}

int main () {
    cout << foo::value() << \n;
    cout << bar::value() << \n;
    cout << bar::pi << \n;
    
    return 0;
}

打印结果

5
6.2832
3.1416
Program ended with exit code: 0

 

 

 

使用命名空间

#include <iostream>
using namespace std;

namespace first {
    int x = 5;
    int y = 10;
}

namespace second {
    double x = 3.1416;
    double y = 2.7183;
}

int main () {
    // 声明使用命名空间中的某个元素
    using first::x;
    using second::y;
    cout << x << \n;
    cout << y << \n;
    
    // 直接使用命名空间中的某个元素
    cout << first::y << \n;
    cout << second::x << \n;
    
    return 0;
}

打印结果

5
2.7183
10
3.1416
Program ended with exit code: 0

 

#include <iostream>
using namespace std;

namespace first {
    int x = 5;
    int y = 10;
}

namespace second {
    double x = 3.1416;
    double y = 2.7183;
}

int main () {
    // 声明使用命名空间first中的元素
    using namespace first;
    cout << x << \n;
    cout << y << \n;
    
    // 使用命名空间second中的元素
    cout << second::x << \n;
    cout << second::y << \n;
    
    return 0;
}

打印结果

5
2.7183
10
3.1416
Program ended with exit code: 0

 

#include <iostream>
using namespace std;

namespace first {
    int x = 5;
}

namespace second {
    double x = 3.1416;
}

int main () {
    // 使用命名空间first
    {
        using namespace first;
        cout << x << \n;
    }
    
    // 使用命名空间second
    {
        using namespace second;
        cout << x << \n;
    }
    
    return 0;
}

打印结果

5
3.1416
Program ended with exit code: 0

 

[C++] 用Xcode来写C++程序[6] Name visibility

标签:

原文地址:http://www.cnblogs.com/YouXianMing/p/4322958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!