Appearance
基础语法
概述
C++是在C语言基础上发展而来的编程语言,增加了面向对象、泛型编程等特性。本节介绍C++的基础语法。
第一个C++程序
cpp
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}使用命名空间
cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}输入输出
cout和cin
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "请输入你的名字: ";
cin >> name;
cout << "请输入你的年龄: ";
cin >> age;
cout << "你好, " << name << "! 你今年 " << age << " 岁。" << endl;
return 0;
}读取一行
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
cout << "请输入一行文字: ";
cin.ignore();
getline(cin, line);
cout << "你输入的是: " << line << endl;
return 0;
}数据类型
基本数据类型
cpp
#include <iostream>
#include <climits>
using namespace std;
int main() {
bool b = true;
char c = 'A';
int i = 42;
short s = 100;
long l = 1000000L;
long long ll = 9223372036854775807LL;
float f = 3.14f;
double d = 3.14159265358979;
long double ld = 3.14159265358979L;
cout << "bool: " << b << endl;
cout << "char: " << c << endl;
cout << "int: " << i << endl;
cout << "float: " << f << endl;
cout << "double: " << d << endl;
return 0;
}auto关键字
cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
auto a = 10;
auto b = 3.14;
auto c = "hello";
auto d = vector<int>{1, 2, 3};
cout << "a的类型: int, 值: " << a << endl;
cout << "b的类型: double, 值: " << b << endl;
cout << "c的类型: const char*, 值: " << c << endl;
return 0;
}变量与常量
const关键字
cpp
#include <iostream>
using namespace std;
int main() {
const int MAX_SIZE = 100;
const double PI = 3.14159;
cout << "MAX_SIZE = " << MAX_SIZE << endl;
cout << "PI = " << PI << endl;
return 0;
}constexpr
cpp
#include <iostream>
using namespace std;
constexpr int square(int x) {
return x * x;
}
int main() {
constexpr int val = square(5);
cout << "5的平方 = " << val << endl;
return 0;
}引用
基本引用
cpp
#include <iostream>
using namespace std;
int main() {
int a = 10;
int &ref = a;
cout << "a = " << a << endl;
cout << "ref = " << ref << endl;
ref = 20;
cout << "修改后 a = " << a << endl;
cout << "修改后 ref = " << ref << endl;
return 0;
}引用作为函数参数
cpp
#include <iostream>
using namespace std;
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void increment(int &n) {
n++;
}
int main() {
int x = 10, y = 20;
cout << "交换前: x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "交换后: x = " << x << ", y = " << y << endl;
int num = 5;
cout << "递增前: " << num << endl;
increment(num);
cout << "递增后: " << num << endl;
return 0;
}常量引用
cpp
#include <iostream>
#include <string>
using namespace std;
void printString(const string &str) {
cout << str << endl;
}
int main() {
string s = "Hello, C++";
printString(s);
printString("World");
return 0;
}默认参数
cpp
#include <iostream>
using namespace std;
int add(int a, int b = 0) {
return a + b;
}
void printInfo(string name, int age = 18, string city = "北京") {
cout << "姓名: " << name << endl;
cout << "年龄: " << age << endl;
cout << "城市: " << city << endl;
cout << "-------------" << endl;
}
int main() {
cout << "add(5) = " << add(5) << endl;
cout << "add(5, 3) = " << add(5, 3) << endl;
printInfo("张三");
printInfo("李四", 25);
printInfo("王五", 30, "上海");
return 0;
}函数重载
cpp
#include <iostream>
#include <string>
using namespace std;
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
string add(const string &a, const string &b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
cout << "int add: " << add(1, 2) << endl;
cout << "double add: " << add(1.5, 2.5) << endl;
cout << "string add: " << add("Hello, ", "World!") << endl;
cout << "三个参数 add: " << add(1, 2, 3) << endl;
return 0;
}内联函数
cpp
#include <iostream>
using namespace std;
inline int square(int x) {
return x * x;
}
inline double cube(double x) {
return x * x * x;
}
int main() {
cout << "5的平方: " << square(5) << endl;
cout << "3的立方: " << cube(3.0) << endl;
return 0;
}命名空间
定义命名空间
cpp
#include <iostream>
namespace Math {
const double PI = 3.14159;
double circleArea(double radius) {
return PI * radius * radius;
}
double circleCircumference(double radius) {
return 2 * PI * radius;
}
}
namespace Physics {
const double G = 9.8;
double freeFall(double time) {
return 0.5 * G * time * time;
}
}
using namespace std;
int main() {
cout << "圆面积 (r=5): " << Math::circleArea(5.0) << endl;
cout << "圆周长 (r=5): " << Math::circleCircumference(5.0) << endl;
cout << "自由落体距离 (t=2s): " << Physics::freeFall(2.0) << endl;
return 0;
}嵌套命名空间
cpp
#include <iostream>
namespace Company {
namespace Department {
namespace HR {
void hire() {
std::cout << "招聘员工" << std::endl;
}
}
namespace IT {
void develop() {
std::cout << "开发软件" << std::endl;
}
}
}
}
int main() {
Company::Department::HR::hire();
Company::Department::IT::develop();
return 0;
}new和delete
动态内存分配
cpp
#include <iostream>
using namespace std;
int main() {
int *ptr = new int;
*ptr = 100;
cout << "动态分配的整数: " << *ptr << endl;
delete ptr;
int *arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = i * 10;
}
cout << "动态数组: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
delete[] arr;
return 0;
}二维数组
cpp
#include <iostream>
using namespace std;
int main() {
int rows = 3, cols = 4;
int **matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = i * cols + j;
}
}
cout << "二维数组:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
return 0;
}string类
基本操作
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "Hello";
string s2 = "World";
string s3 = s1 + " " + s2;
cout << "拼接: " << s3 << endl;
cout << "长度: " << s3.length() << endl;
cout << "是否为空: " << (s3.empty() ? "是" : "否") << endl;
s3.append("!");
cout << "追加后: " << s3 << endl;
s3.insert(5, ",");
cout << "插入后: " << s3 << endl;
s3.erase(5, 1);
cout << "删除后: " << s3 << endl;
cout << "子串: " << s3.substr(0, 5) << endl;
size_t pos = s3.find("World");
if (pos != string::npos) {
cout << "找到World在位置: " << pos << endl;
}
return 0;
}字符串比较
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "apple";
string s2 = "banana";
string s3 = "apple";
cout << "s1 == s3: " << (s1 == s3 ? "true" : "false") << endl;
cout << "s1 < s2: " << (s1 < s2 ? "true" : "false") << endl;
cout << "s1.compare(s2): " << s1.compare(s2) << endl;
return 0;
}异常处理
try-catch
cpp
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double a, double b) {
if (b == 0) {
throw runtime_error("除数不能为零");
}
return a / b;
}
int main() {
try {
cout << "10 / 2 = " << divide(10, 2) << endl;
cout << "10 / 0 = " << divide(10, 0) << endl;
} catch (const runtime_error &e) {
cout << "捕获异常: " << e.what() << endl;
}
return 0;
}自定义异常
cpp
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
class InsufficientFundsException : public runtime_error {
public:
InsufficientFundsException(double balance, double amount)
: runtime_error("余额不足"), balance(balance), amount(amount) {}
double getBalance() const { return balance; }
double getAmount() const { return amount; }
private:
double balance;
double amount;
};
class BankAccount {
public:
BankAccount(double initialBalance) : balance(initialBalance) {}
void withdraw(double amount) {
if (amount > balance) {
throw InsufficientFundsException(balance, amount);
}
balance -= amount;
cout << "取款成功,余额: " << balance << endl;
}
double getBalance() const { return balance; }
private:
double balance;
};
int main() {
BankAccount account(1000);
try {
account.withdraw(500);
account.withdraw(800);
} catch (const InsufficientFundsException &e) {
cout << e.what() << endl;
cout << "当前余额: " << e.getBalance() << endl;
cout << "尝试取款: " << e.getAmount() << endl;
}
return 0;
}类型转换
C++风格类型转换
cpp
#include <iostream>
using namespace std;
int main() {
double d = 3.14159;
int i1 = static_cast<int>(d);
cout << "static_cast: " << i1 << endl;
const int ci = 10;
int &ref = const_cast<int&>(ci);
cout << "const_cast: " << ref << endl;
int *ptr = reinterpret_cast<int*>(0x1000);
cout << "reinterpret_cast: " << ptr << endl;
return 0;
}实践示例
计算器程序
cpp
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
class Calculator {
public:
double calculate(double a, double b, char op) {
switch (op) {
case '+': return add(a, b);
case '-': return subtract(a, b);
case '*': return multiply(a, b);
case '/': return divide(a, b);
default: throw invalid_argument("无效的运算符");
}
}
private:
double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }
double multiply(double a, double b) { return a * b; }
double divide(double a, double b) {
if (b == 0) throw runtime_error("除数不能为零");
return a / b;
}
};
int main() {
Calculator calc;
while (true) {
double a, b;
char op;
cout << "\n请输入表达式 (如 5 + 3, 输入 q 退出): ";
cin >> a;
if (cin.fail()) {
string input;
cin.clear();
cin >> input;
if (input == "q") break;
cout << "输入无效,请重试" << endl;
continue;
}
cin >> op >> b;
try {
double result = calc.calculate(a, b, op);
cout << a << " " << op << " " << b << " = " << result << endl;
} catch (const exception &e) {
cout << "错误: " << e.what() << endl;
}
}
cout << "再见!" << endl;
return 0;
}学生成绩管理
cpp
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
struct Student {
string name;
int id;
vector<double> scores;
double getAverage() const {
if (scores.empty()) return 0;
double sum = 0;
for (double s : scores) sum += s;
return sum / scores.size();
}
double getTotal() const {
double sum = 0;
for (double s : scores) sum += s;
return sum;
}
};
class GradeManager {
public:
void addStudent(const string &name, int id) {
students.push_back({name, id, {}});
cout << "添加学生成功: " << name << endl;
}
void addScore(int id, double score) {
for (auto &s : students) {
if (s.id == id) {
s.scores.push_back(score);
cout << "添加成绩成功" << endl;
return;
}
}
cout << "未找到学生" << endl;
}
void displayAll() const {
cout << "\n" << string(60, '=') << endl;
cout << left << setw(10) << "学号"
<< setw(15) << "姓名"
<< setw(15) << "总分"
<< setw(15) << "平均分" << endl;
cout << string(60, '-') << endl;
for (const auto &s : students) {
cout << left << setw(10) << s.id
<< setw(15) << s.name
<< setw(15) << fixed << setprecision(2) << s.getTotal()
<< setw(15) << s.getAverage() << endl;
}
cout << string(60, '=') << endl;
}
void findStudent(int id) const {
for (const auto &s : students) {
if (s.id == id) {
cout << "\n学生信息:" << endl;
cout << "学号: " << s.id << endl;
cout << "姓名: " << s.name << endl;
cout << "成绩: ";
for (double score : s.scores) {
cout << score << " ";
}
cout << "\n总分: " << s.getTotal() << endl;
cout << "平均分: " << s.getAverage() << endl;
return;
}
}
cout << "未找到学号为 " << id << " 的学生" << endl;
}
private:
vector<Student> students;
};
int main() {
GradeManager manager;
manager.addStudent("张三", 1001);
manager.addStudent("李四", 1002);
manager.addStudent("王五", 1003);
manager.addScore(1001, 85);
manager.addScore(1001, 90);
manager.addScore(1001, 78);
manager.addScore(1002, 92);
manager.addScore(1002, 88);
manager.addScore(1003, 76);
manager.addScore(1003, 82);
manager.addScore(1003, 90);
manager.displayAll();
manager.findStudent(1001);
return 0;
}小结
C++基础语法要点:
| 特性 | 说明 |
|---|---|
| 引用 | 变量的别名,必须初始化 |
| const | 定义常量,不可修改 |
| auto | 自动类型推导 |
| 函数重载 | 同名函数,不同参数 |
| 默认参数 | 函数参数默认值 |
| 命名空间 | 避免命名冲突 |
| new/delete | 动态内存管理 |
| string | 字符串类 |