C++有许多经典的程序示例,以下是其中一些简单但常见的例子,以帮助你更好地了解C++语言的基本概念。
- **Hello World程序:**
```cpp
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
```
- **计算器程序:**
```cpp
#include <iostream>
int main() {
double num1, num2, result;
char op;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter operator (+, -, *, /): ";
std::cin >> op;
std::cout << "Enter second number: ";
std::cin >> num2;
switch(op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if(num2 != 0)
result = num1 / num2;
else {
std::cout << "Error! Division by zero." << std::endl;
return 1; // Exit with an error code
}
break;
default:
std::cout << "Error! Invalid operator." << std::endl;
return 1; // Exit with an error code
}
std::cout << "Result: " << result << std::endl;
return 0;
}
```
- **循环程序:**
```cpp
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << "Iteration " << i << std::endl;
}
return 0;
}
```
- **数组和循环:**
```cpp
#include <iostream>
int main() {
const int size = 5;
int numbers[size] = {1, 2, 3, 4, 5};
std::cout << "Array elements: ";
for (int i = 0; i < size; ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
当然,接下来是一些稍微复杂一点的C++程序,涉及到函数、类和文件操作等方面:
- **函数示例:**
```cpp
#include <iostream>
// 函数声明
int add(int a, int b);
int main() {
int num1, num2, sum;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter second number: ";
std::cin >> num2;
// 调用函数
sum = add(num1, num2);
std::cout << "Sum: " << sum << std::endl;
return 0;
}
// 函数定义
int add(int a, int b) {
return a + b;
}
```
- **类和对象示例:**
```cpp
#include <iostream>
// 类的声明
class Rectangle {
public:
double length;
double width;
double calculateArea();
};
// 类的成员函数定义
double Rectangle::calculateArea() {
return length * width;
}
int main() {
// 创建对象
Rectangle rect;
// 初始化对象的属性
rect.length = 5.0;
rect.width = 3.0;
// 调用对象的方法
double area = rect.calculateArea();
std::cout << "Area of the rectangle: " << area << std::endl;
return 0;
}
```
- **文件操作示例:**
```cpp
#include <iostream>
#include <fstream>
int main() {
std::ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, File!\n";
outFile << "This is a C++ file example.\n";
outFile.close();
std::cout << "File written successfully.\n";
} else {
std::cout << "Unable to open file.\n";
}
return 0;
}
```
- **递归函数:**
```cpp
#include <iostream>
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << "Factorial of " << num << ": " << factorial(num) << std::endl;
return 0;
}
```
- **链表:**
```cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
int main() {
// 略,包括链表的创建、插入和打印等操作
return 0;
}
```
- **异常处理:**
```cpp
#include <iostream>
int main() {
try {
// 程序代码,可能引发异常
} catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception caught." << std::endl;
}
return 0;
}
```
- **多线程:**
```cpp
#include <iostream>
#include <thread>
void printNumbers() {
for (int i = 1; i <= 5; ++i) {
std::cout << "Thread: " << i << std::endl;
}
}
int main() {
std::thread t(printNumbers);
t.join(); // 等待线程结束
return 0;
}
```
- **文件读取和写入:**
```cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inFile("input.txt");
std::ofstream outFile("output.txt");
if (inFile.is_open() && outFile.is_open()) {
std::string line;
while (std::getline(inFile, line)) {
// 处理每一行数据
outFile << line << std::endl;
}
inFile.close();
outFile.close();
} else {
std::cout << "Unable to open files." << std::endl;
}
return 0;
}
```
- **面向对象继承:**
```cpp
#include <iostream>
// 基类
class Shape {
public:
virtual double area() const = 0; // 纯虚函数,表示需要在派生类中实现
};
// 派生类
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14 * radius * radius;
}
};
int main() {
Circle circle(5.0);
std::cout << "Area of the circle: " << circle.area() << std::endl;
return 0;
}
```
- **模板:**
```cpp
#include <iostream>
// 函数模板
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
std::cout << "Sum of integers: " << add(5, 7) << std::endl;
std::cout << "Sum of doubles: " << add(3.14, 2.71) << std::endl;
return 0;
}
```
- **STL容器:**
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
- **STL算法:**
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 6};
// 使用STL算法对容器进行排序
std::sort(numbers.begin(), numbers.end());
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
- **Lambda表达式:**
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 使用Lambda表达式对每个元素进行平方操作
std::for_each(numbers.begin(), numbers.end(), [](int& num) {
num = num * num;
});
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
- **网络编程基础:**
```cpp
// 编写一个简单的TCP服务器或客户端程序,涉及socket编程
// 这里可能涉及到很多代码,可以参考相关网络编程的C++库或教程
```
- **图形用户界面(GUI)应用:**
```cpp
// 使用Qt或其他GUI库创建一个简单的窗口应用程序
// 这里可能涉及到GUI库的使用,事件处理等
```
- **数据结构 - 栈:**
```cpp
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
myStack.push(1);
myStack.push(2);
myStack.push(3);
while (!myStack.empty()) {
std::cout << myStack.top() << " ";
myStack.pop();
}
std::cout << std::endl;
return 0;
}
```
- **数据结构 - 队列:**
```cpp
#include <iostream>
#include <queue>
int main() {
std::queue<int> myQueue;
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
while (!myQueue.empty()) {
std::cout << myQueue.front() << " ";
myQueue.pop();
}
std::cout << std::endl;
return 0;
}
```
- **多态和虚函数:**
```cpp
#include <iostream>
// 基类
class Animal {
public:
virtual void makeSound() const {
std::cout << "Animal makes a sound" << std::endl;
}
};
// 派生类
class Dog : public Animal {
public:
void makeSound() const override {
std::cout << "Dog barks" << std::endl;
}
};
int main() {
Animal* animalPtr = new Dog();
animalPtr->makeSound(); // 调用派生类的虚函数
delete animalPtr;
return 0;
}
```
- **数据库连接:**
```cpp
// 使用C++连接数据库,例如MySQL、SQLite等
// 这里可能涉及到数据库API的使用,SQL查询等
```
- **正则表达式:**
```cpp
#include <iostream>
#include <regex>
int main() {
std::string text = "Hello, 12345!";
std::regex pattern("\\d+");
if (std::regex_search(text, pattern)) {
std::cout << "Numbers found in the text." << std::endl;
} else {
std::cout << "No numbers found in the text." << std::endl;
}
return 0;
}
```
- **游戏编程基础:**
```cpp
// 编写一个简单的控制台游戏,涉及到游戏循环、用户输入处理等
```
- **OpenGL图形编程:**
```cpp
// 使用OpenGL库进行简单的图形渲染,例如绘制三角形
// 这里可能涉及到OpenGL的初始化,渲染循环等
```
- **Web服务器:**
```cpp
// 编写一个简单的Web服务器,处理HTTP请求
// 这里可能涉及到socket编程、HTTP协议解析等
```
- **单元测试:**
```cpp
// 使用C++的单元测试框架,例如
Catch2 或 Google Test,编写一些简单的测试用例来验证程序的正确性。
```cpp
#define CATCH_CONFIG_MAIN
#include <iostream>
#include "catch.hpp"
// 示例类
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
};
// 测试用例
TEST_CASE("Calculator addition", "[Calculator]") {
Calculator calc;
REQUIRE(calc.add(2, 3) == 5);
REQUIRE(calc.add(-1, 1) == 0);
REQUIRE(calc.add(0, 0) == 0);
}
TEST_CASE("Calculator multiplication", "[Calculator]") {
Calculator calc;
REQUIRE(calc.multiply(2, 3) == 6);
REQUIRE(calc.multiply(-2, 3) == -6);
REQUIRE(calc.multiply(0, 5) == 0);
}
```
- **XML或JSON解析:**
```cpp
// 使用第三方库(如pugixml或jsoncpp)解析和生成XML或JSON数据
// 这里可能涉及到文件读取、数据结构映射等
```
- **机器学习基础:**
```cpp
// 使用开源机器学习库(如Eigen、MLPack)进行简单的线性回归或分类任务
// 这里可能涉及到矩阵运算、模型训练和预测等
```
这是一系列更高级的示例,涉及到面向对象设计、数据结构、网络编程、图形编程、数据库连接、正则表达式、游戏编程、OpenGL图形编程、Web服务器、单元测试、XML/JSON解析、机器学习等方面。你可以选择其中感兴趣或适合你学习目标的主题进行深入学习。每个示例都可能需要额外的学习和研究,以理解相关的概念和技术。