C++ 是一种强大的通用型语言,由 Bjarne Stroustrup 开发,旨在扩展 C 语言的功能,融合面向对象编程的特性。C++ 的应用广泛,从系统级编程到游戏开发、高性能计算等多个领域。
# 对于 Debian/Ubuntu 用户: sudo apt-get install g++ -y # 配置 GCC echo 'export PATH="/usr/bin:/usr/local/bin:$PATH"' >> ~/.bashrc source ~/.bashrc基本语法学习
#include <iostream> int main() { int age = 25; double pi = 3.14159; char letter = 'B'; std::cout << "整型: " << age << ", 浮点型: " << pi << ", 字符型: " << letter << std::endl; return 0; }
#include <iostream> int main() { int num1 = 5, num2 = 3; std::cout << "加法: " << num1 + num2 << std::endl; std::cout << "减法: " << num1 - num2 << std::endl; std::cout << "乘法: " << num1 * num2 << std::endl; std::cout << "除法: " << num1 / num2 << std::endl; std::cout << "取余: " << num1 % num2 << std::endl; return 0; }
#include <iostream> int main() { int x = 10; if (x > 5) { std::cout << "x 大于 5" << std::endl; } else { std::cout << "x 小于或等于 5" << std::endl; } int y = 2; while (y < 10) { std::cout << y << std::endl; y++; } return 0; }函数与模块化编程
#include <iostream> int square(int num) { return num * num; } int main() { int result = square(5); std::cout << "结果是: " << result << std::endl; return 0; }
#include <iostream> void printValue(int& value) { std::cout << "值: " << value << std::endl; } int main() { int num = 10; printValue(num); return 0; }
#include <iostream> class Math { public: int add(int a, int b) { return a + b; } }; int main() { Math mathObj; std::cout << "加法结果: " << mathObj.add(3, 4) << std::endl; return 0; }面向对象编程
#include <iostream> class Account { public: void deposit(int amount) { balance += amount; } private: int balance = 0; }; int main() { Account myAccount; myAccount.deposit(100); std::cout << "余额: " << myAccount.balance << std::endl; return 0; }
#include <iostream> class Vehicle { public: virtual void move() { std::cout << "移动" << std::endl; } }; class Car : public Vehicle { public: void move() override { std::cout << "汽车移动" << std::endl; } }; int main() { Vehicle* vehicle = new Car; vehicle->move(); delete vehicle; return 0; }
#include <iostream> class MyClass { int value; public: MyClass(int x) : value(x) {} MyClass operator+(const MyClass& other) const { return MyClass(value + other.value); } }; int main() { MyClass a(3); MyClass b(4); MyClass c = a + b; std::cout << "结果是: " << c.value << std::endl; return 0; }错误处理与调试
#include <iostream> #include <exception> class MyException : public std::exception { public: const char* what() const throw () { return "我的异常"; } }; int main() { try { throw MyException(); } catch (std::exception& e) { std::cout << "捕获到异常: " << e.what() << std::endl; } return 0; }
在代码中加入调试语句或使用 IDE 的调试功能。
#include <iostream> int main() { int sum = 0; for (int i = 0; i < 1000000; ++i) { sum += i; } std::cout << "求和结果是: " << sum << std::endl; return 0; }实战项目与资源推荐
通过上述资源和实践项目,你可以系统性地学习 C++,从基础语法掌握到面向对象编程的高级概念,逐步提升编程技能。实践是学习编程的关键,因此,通过完成上述项目和阅读推荐资源,将有助于深化理解并熟练运用 C++。