C++ 核心代码通常指一些基础、常用的代码片段,可以用于各种C++项目中,包括输入输出、基本数据结构、算法实现等。下面是一些典型的 C++ 核心代码示例:
1. 基本输入输出
cpp
include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Sum: " << (a + b) << endl;
return 0;
}
2. 使用函数
cpp
include <iostream>
using namespace std;
int add(int x, int y) {
return x + y;
}
int main() {
int a = 5, b = 10;
cout << "Sum: " << add(a, b) << endl;
return 0;
}
3. 类与对象
cpp
include <iostream>
using namespace std;
class Rectangle {
public:
int width, height;
Rectangle(int w, int h) : width(w), height(h) {}
int area() {
return width * height;
}
};
int main() {
Rectangle rect(5, 10);
cout << "Area: " << rect.area() << endl;
return 0;
}
4. 使用向量(std::vector)
cpp
include <iostream>
include <vector>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
cout << num << " ";
}
cout << endl;
return 0;
}
5. 排序算法示例(std::sort)
cpp
include <iostream>
include <algorithm>
include <vector>
using namespace std;
int main() {
vector<int> nums = {5, 3, 8, 1, 2};
sort(nums.begin(), nums.end());
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
6. 指针和动态内存分配
cpp
include <iostream>
using namespace std;
int main() {
int* p = new int(10); // 动态分配内存
cout << "Value: " << *p << endl;
delete p; // 释放内存
return 0;
}
7. 模板函数
cpp
include <iostream>
using namespace std;
template <typename T>
T add(T x, T y) {
return x + y;
}
int main() {
cout << "Int Sum: " << add(3, 5) << endl;
cout << "Double Sum: " << add(3.5, 5.5) << endl;
return 0;
}
8. 异常处理
cpp
include <iostream>
using namespace std;
int divide(int a, int b) {
if (b == 0) {
throw runtime_error("Division by zero!");
}
return a / b;
}
int main() {
try {
cout << "Result: " << divide(10, 0) << endl;
} catch (const runtime_error& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
这些代码片段展示了 C++ 核心编程中的一些基本概念。掌握这些基础知识能帮助你在 C++ 编程中打好扎实的基础。
标签:std,cout,int,核心,代码,namespace,C++,using,main
From: https://blog.csdn.net/nbspzs/article/details/143684353