目录
前言
C++ 入门基础:命名空间、输入输出、缺省参数与函数重载
1. 命名空间(Namespace)
什么是命名空间?
在 C++ 中,命名空间(namespace) 用于解决变量、函数、类等标识符命名冲突的问题。通过使用命名空间,可以将相同名称的标识符放在不同的逻辑区域内,从而避免冲突。
语法
#include <iostream>
using namespace std;
namespace A {
void display() {
cout << "This is namespace A" << endl;
}
}
namespace B {
void display() {
cout << "This is namespace B" << endl;
}
}
int main() {
A::display(); // 调用 A 命名空间的 display()
B::display(); // 调用 B 命名空间的 display()
return 0;
}
使用 using 关键字
using namespace A;
display(); // 直接调用 A::display(),无需使用 A::
2. C++ 输入与输出
基本输入输出
C++ 提供 cin 和 cout 进行输入输出,分别来自 <iostream> 头文件。
输出(cout)
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!" << endl;
return 0;
}
- << 称为插入运算符,将数据输出到控制台。
- endl 表示换行。
输入(cin)
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age; // 从键盘获取输入
cout << "Your age is: " << age << endl;
return 0;
}
- >> 称为提取运算符,用于从输入流中获取数据。
3. 缺省参数(Default Arguments)
什么是缺省参数?
缺省参数允许在调用函数时省略某些参数,省略时会使用函数定义时指定的默认值。
语法
#include <iostream>
using namespace std;
void greet(string name = "Guest") {
cout << "Hello, " << name << "!" << endl;
}
int main() {
greet(); // 使用默认参数
greet("John"); // 传递参数时覆盖默认值
return 0;
}
- greet() → 输出 Hello, Guest!
- greet("John") → 输出 Hello, John!
注意事项
- 缺省参数必须从右向左依次提供。
- 定义时可以为多个参数设置默认值,但中间不能跳过。
4. 函数重载(Function Overloading)
什么是函数重载?
函数重载 允许在同一个作用域中定义多个同名函数,只要它们的参数类型或参数个数不同。
语法
#include <iostream>
using namespace std;
// 重载 add 函数
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
cout << add(5, 10) << endl; // 调用 int 版本
cout << add(5.5, 10.5) << endl; // 调用 double 版本
cout << add(5, 10, 15) << endl; // 调用 3 个参数的版本
return 0;
}
解析
- add(5, 10) → 匹配 int add(int, int)
- add(5.5, 10.5) → 匹配 double add(double, double)
- add(5, 10, 15) → 匹配 int add(int, int, int)
总结
- 命名空间 解决命名冲突,可以通过 using 关键字简化访问。
- C++ 输入输出 使用 cin 和 cout 进行基本的控制台交互。
- 缺省参数 允许函数使用默认值来减少参数传递。
- 函数重载 允许使用相同的函数名处理不同的数据类型或参数数量,提高代码的灵活性。