- gf25152 的博客
c++代码框架
- @ 2026-4-12 16:14:27
C++11:
// 确保使用 C++11 标准编译
// g++ main.cpp -std=c++11 -o app
#include <iostream>
#include <string>
#include <vector>
#include <memory> // C++11 智能指针
#include <algorithm>
// 禁用不安全函数警告(Windows 可选)
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif
// 命名空间
namespace MyApp {
// C++11 类示例
class Demo {
public:
// 构造函数
Demo(int id, const std::string& name)
: m_id(id), m_name(name) {}
// 常量成员函数
void show() const {
std::cout << "ID: " << m_id
<< " Name: " << m_name << std::endl;
}
// Getter
int id() const { return m_id; }
private:
int m_id;
std::string m_name;
};
} // namespace MyApp
// 主函数
int main() {
// 1. 自动类型推导 C++11 auto
auto num = 10;
auto str = std::string("Hello C++11");
// 2. 范围 for 循环 C++11
std::vector<int> vec = {1, 2, 3, 4, 5};
std::cout << "Vector: ";
for (auto x : vec) {
std::cout << x << " ";
}
std::cout << std::endl;
// 3. 智能指针 unique_ptr C++11
std::unique_ptr<MyApp::Demo> pDemo =
std::make_unique<MyApp::Demo>(101, "TestObj");
pDemo->show();
// 4. Lambda 表达式 C++11
std::cout << "Lambda sort descending: ";
std::sort(vec.begin(), vec.end(), [](sslocal://flow/file_open?url=int+a%2C+int+b&flow_extra=eyJsaW5rX3R5cGUiOiJjb2RlX2ludGVycHJldGVyIn0=) {
return a > b;
});
for (auto x : vec) {
std::cout << x << " ";
}
std::cout << std::endl;
// 5. nullptr C++11
int* ptr = nullptr;
if (ptr == nullptr) {
std::cout << "ptr is null" << std::endl;
}
// 6. 移动语义简化示例
std::string s1 = "hello";
std::string s2 = std::move(s1);
std::cout << "s2: " << s2 << std::endl;
return 0;
}
C++23:
// 编译命令(GCC 13+/Clang 17+/VS2022)
// g++ -std=c++23 -O2 -Wall main.cpp -o app
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <expected> // C++23
#include <print> // C++23
#include <ranges> // C++20/23
#include <concepts> // C++20
// C++20 概念约束
template<std::integral T>
T square(T x) {
return x * x;
}
// C++23 std::expected 错误处理
std::expected<int, std::string> divide(int a, int b) noexcept {
if (b == 0)
return std::unexpected{"divide by zero"};
return a / b;
}
int main() {
// C++23 std::print / std::println
std::println("=== C++23 Framework ===");
// 范围 + 视图
auto nums = std::vector{1,2,3,4,5};
auto squared = nums
| std::views::transform([](sslocal://flow/file_open?url=int+x&flow_extra=eyJsaW5rX3R5cGUiOiJjb2RlX2ludGVycHJldGVyIn0=) { return square(x); });
std::print("squared: ");
for (auto x : squared) std::print("{} ", x);
std::println("");
// C++23 expected 错误处理
auto res = divide(10, 2);
if (res) {
std::println("10/2 = {}", *res);
} else {
std::println("error: {}", res.error());
}
// 字符串 contains (C++23)
std::string s = "hello c++23";
if (s.contains("c++23")) {
std::println("string contains 'c++23'");
}
// if constexpr (C++17)
if constexpr (sizeof(int) == 4) {
std::println("int is 4 bytes");
}
return 0;
}