跳到主要内容
C++ 编程笔记:基础语法、核心特性与项目练习 | 极客日志
C++
C++ 编程笔记:基础语法、核心特性与项目练习 涵盖环境搭建、基本语法、函数、类与对象、继承多态、模板、异常处理、文件操作、标准库及高级特性,配合代码示例和综合项目实践,提供一条从基础到实战的学习路径。
这份笔记整理了我认为 C++ 入门需要掌握的核心点,从环境配置到类、模板、异常处理,再到一些高级特性,附带代码示例。适合有一点点编程经验的人快速上手。
C++ 简介
C++ 由 Bjarne Stroustrup 于 1979 年起初作为'C with Classes'开发,1985 年发布首个版本,后经 C++98/03/11/14/17/20 等标准迭代。它支持面向对象、泛型和过程式编程,高效的内存管理适合系统级开发,STL 提供了丰富的容器和算法。主要应用在系统软件、游戏、嵌入式等领域。
环境搭建
安装编译器和 IDE
Windows 可选 MinGW 或 Visual Studio;Linux 用 sudo apt install g++;Mac 可用 brew install gcc。安装后确保编译器在 PATH 中。
编译运行示例
创建 hello.cpp:
#include <iostream>
using namespace std;
int main () {
cout << "Hello, C++!" << endl;
return 0 ;
}
编译运行:
g++ hello.cpp -o hello
./hello
基本语法
C++ 程序结构包括头文件、主函数等。注释用 // 单行,/* */ 多行。
数据类型
内置类型:bool, char, int, float, double, void, wchar_t,可用 signed/unsigned/short/long 修饰。存储大小因系统而异,常见 64 位系统下:
类型 字节 范围 char 1 -128~127 unsigned char 1 0~255 int 4 -2147483648~2147483647 long long 8 -9e18~9e18 double 8 ±1.7e±308
这段代码输出当前系统的类型大小:
#include <iostream>
#include <limits>
using namespace std;
{
cout << << endl;
cout << << ( ) << << numeric_limits< >:: () << endl;
cout << << ( ) << << numeric_limits< >:: () << endl;
cout << << ( ) << << numeric_limits< >:: () << endl;
cout << << ( ) << << numeric_limits< >:: () << endl;
;
}
int main ()
"type:\t\tsize\tmax\tmin"
"bool:\t\t"
sizeof
bool
"\t"
bool
max
"char:\t\t"
sizeof
char
"\t"
char
max
"int:\t\t"
sizeof
int
"\t"
int
max
"double:\t\t"
sizeof
double
"\t"
double
max
return
0
常量和输入输出 const float gravity = 9.81; 定义常量。用 cin 和 cout 交互:
int number;
cout << "请输入一个数字:" ;
cin >> number;
cout << "你输入的数字是:" << number << endl;
控制结构
if-else 与 switch int a = 10 ;
if (a > 0 ) {
cout << "a 是正数" << endl;
} else {
cout << "a 不是正数" << endl;
}
int day = 4 ;
switch (day) {
case 1 : cout << "星期一" << endl; break ;
case 2 : cout << "星期二" << endl; break ;
default : cout << "不是工作日" << endl;
}
循环 for (int i = 0 ; i < 5 ; i++) {
cout << "i 的值:" << i << endl;
}
int j = 0 ;
while (j < 5 ) {
cout << "j 的值:" << j << endl;
j++;
}
int k = 0 ;
do {
cout << "k 的值:" << k << endl;
k++;
} while (k < 5 );
函数 int add (int a, int b) {
return a + b;
}
void modify (int &num) {
num += 10 ;
}
int x = 5 ;
modify (x);
float multiply (float a, float b) { return a * b; }
int multiply (int a, int b) { return a * b; }
void greet (string name = "World" ) {
cout << "Hello, " << name << "!" << endl;
}
inline int square (int x) {
return x * x;
}
auto add = [](int a, int b) { return a + b; };
cout << "Lambda add: " << add (5 , 3 ) << endl;
数组与字符串 int arr[5 ] = {1 , 2 , 3 , 4 , 5 };
for (int i = 0 ; i < 5 ; i++) {
cout << arr[i] << " " ;
}
int matrix[2 ][3 ] = {{1 , 2 , 3 }, {4 , 5 , 6 }};
for (int i = 0 ; i < 2 ; i++) {
for (int j = 0 ; j < 3 ; j++) {
cout << matrix[i][j] << " " ;
}
}
string str = "Hello, World!" ;
cout << "长度:" << str.length () << endl;
str += " C++" ;
cout << str << endl;
指针与引用 int a = 10 ;
int *p = &a;
cout << *p << endl;
int arr[3 ] = {1 ,2 ,3 };
int *p = arr;
cout << *(p+1 ) << endl;
int b = 20 ;
int &r = b;
r = 30 ;
cout << b << endl;
int *ptr = new int ;
*ptr = 42 ;
cout << *ptr << endl;
delete ptr;
结构体与联合体 struct Person {
string name;
int age;
};
Person p = {"Alice" , 30 };
Person people[2 ] = {{"Alice" ,30 }, {"Bob" ,25 }};
for (int i=0 ; i<2 ; ++i)
cout << people[i].name << " " << people[i].age << endl;
union Data {
int intValue;
float floatValue;
};
Data data;
data.intValue = 10 ;
enum Color { RED, GREEN, BLUE };
Color c = GREEN;
类与对象 class Car {
public :
string brand;
int year;
void display () {
cout << brand << ", " << year << endl;
}
};
Car myCar = {"Toyota" , 2020 };
class Point {
public :
int x, y;
Point (int xVal, int yVal) : x (xVal), y (yVal) {}
};
class Circle {
public :
double radius;
double area () { return 3.14 *radius*radius; }
};
访问控制:public、private、protected。
class Box {
private :
double width;
public :
void setWidth (double w) { width = w; }
double getWidth () { return width; }
};
继承与多态 class Animal {
public :
void eat () { cout << "Eating..." << endl; }
};
class Dog : public Animal {
public :
void bark () { cout << "Barking..." << endl; }
};
class Base {
public :
virtual void show () { cout << "Base" << endl; }
};
class Derived : public Base {
public :
void show () override { cout << "Derived" << endl; }
};
Base* ptr = new Derived ();
ptr->show ();
delete ptr;
模板与泛型编程 template <typename T>
T add (T a, T b) { return a + b; }
template <typename T>
class Pair {
T first, second;
public :
Pair (T a, T b) : first (a), second (b) {}
T getFirst () { return first; }
};
template <>
class Pair <string> {
string first, second;
public :
Pair (string a, string b) : first (a), second (b) {}
string getConcatenated () { return first + second; }
};
#include <vector>
#include <algorithm>
vector<int > vec = {5 ,3 ,1 ,4 ,2 };
sort (vec.begin (), vec.end ());
for (int n : vec) cout << n << " " ;
异常处理 try {
throw runtime_error ("出错" );
} catch (const runtime_error& e) {
cout << e.what () << endl;
}
class MyException : public exception {
string message;
public :
MyException (const string& msg) : message (msg) {}
const char * what () const noexcept override { return message.c_str (); }
};
void riskyFunction (int value) {
if (value < 0 ) throw MyException ("负数错误" );
}
try {
riskyFunction (-1 );
} catch (const MyException& e) {
cout << e.what () << endl;
}
文件操作 #include <fstream>
ofstream outFile ("example.txt" ) ;
outFile << "Hello, file!" << endl;
outFile.close ();
ifstream inFile ("example.txt" ) ;
string line;
while (getline (inFile, line)) {
cout << line << endl;
}
inFile.close ();
ofstream outFile ("bin.dat" , ios::binary) ;
int num = 42 ;
outFile.write (reinterpret_cast <char *>(&num), sizeof (num));
outFile.close ();
fstream file ("example.txt" , ios::in | ios::out | ios::app) ;
file << "追加内容" << endl;
file.seekg (0 );
标准库与命名空间 常用库:vector、algorithm。命名空间:
namespace MyNamespace {
void display () { cout << "Hello from MyNamespace!" << endl; }
}
MyNamespace::display ();
高级特性 #include <memory>
unique_ptr<int > ptr (new int (10 )) ;
shared_ptr<int > p1 = make_shared <int >(20 );
vector<int > vec = {1 ,2 ,3 ,4 ,5 };
for_each(vec.begin (), vec.end (), [](int n) { cout << n << " " ; });
C++11/14/17/20 新特性简介:auto、范围 for、nullptr、线程库、泛型 lambda、结构化绑定、if constexpr、optional、concept、ranges 等。
综合项目 设计一个简单项目,使用面向对象思想,版本控制(Git),调试工具(GDB 或 IDE),进行测试和优化。这里略去具体代码,重点是规划模块和类。
学习资源
《C++ Primer》《Effective C++》《The C++ Programming Language》
在线课程:Coursera, edX, Udacity
参与开源项目,加入 C++ 社区(Stack Overflow 等)
附录 关键字列表:class, public, private, virtual, template 等。
常用 STL 算法:sort, find, copy, transform 等。
相关免费在线工具 Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
Markdown转HTML 将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
HTML转Markdown 将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online
JSON 压缩 通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online
JSON美化和格式化 将JSON字符串修饰为友好的可读格式。 在线工具,JSON美化和格式化在线工具,online