1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
#include <iostream>
#include <vector>
#include <string>
namespace Graphics
{
class Point
{
public:
int x, y;
Point(int x, int y) : x(x), y(y) {}
void Print() const { std::cout << "Point(" << x << ", " << y << ")" << std::endl; }
};
class Color
{
public:
int r, g, b;
Color(int r, int g, int b) : r(r), g(g), b(b) {}
void Print() const { std::cout << "Color(" << r << ", " << g << ", " << b << ")" << std::endl; }
};
void DrawLine(const Point& start, const Point& end)
{
std::cout << "Drawing line from ";
start.Print();
std::cout << " to ";
end.Print();
}
}
namespace Math
{
const double PI = 3.14159;
double CalculateArea(double radius)
{
return PI * radius * radius;
}
class Vector
{
public:
double x, y;
Vector(double x, double y) : x(x), y(y) {}
void Print() const { std::cout << "Vector(" << x << ", " << y << ")" << std::endl; }
};
}
int main()
{
std::cout << "=== Using Declarations and Directives ===" << std::endl;
// 1. 不使用using,完全限定名
Graphics::Point p1(10, 20);
Graphics::Color red(255, 0, 0);
p1.Print();
red.Print();
// 2. using声明 - 引入特定的名称
using Graphics::Point;
using Math::PI;
Point p2(30, 40); // 现在可以直接使用Point
p2.Print();
std::cout << "PI = " << PI << std::endl;
// 3. using指令 - 引入整个命名空间
{
using namespace Math; // 局部作用域中使用
Vector v(1.0, 2.0);
v.Print();
double area = CalculateArea(5.0);
std::cout << "Circle area: " << area << std::endl;
}
// 4. 标准库的using
using std::cout;
using std::endl;
using std::string;
cout << "Using std declarations" << endl;
string message = "Hello, World!";
cout << message << endl;
// 5. using namespace std(不推荐在头文件中使用)
{
using namespace std;
vector<int> numbers = {1, 2, 3, 4, 5};
cout << "Vector size: " << numbers.size() << endl;
}
return 0;
}
|