1. extern 声明与 extern "C"
- extern 声明:仅声明变量或函数而不分配内存,通常用于头文件中共享全局变量或函数声明。
- extern "C":强制以 C 语言方式编译函数,避免 C++ 的名称修饰(name mangling)。常用于 C/C++ 混合编程。
#ifdef __cplusplus
extern "C" {
void c_style_function();
}
#endif
2. static、inline 与 const
- 限制作用域为当前源文件(文件作用域)。
- 静态成员变量需在类外定义,静态成员函数不能访问非静态成员。
- 建议编译器内联展开函数体,适用于短小且频繁调用的函数。
- 只能被常量对象调用,且不能修改成员变量(除非变量标记为
mutable)。
const 成员函数:
class ConstExample {
mutable int modifiable;
public:
void const_func() const {
modifiable = 1;
}
};
inline:
inline int add(int a, int b) {
return a + b;
}
static:
class Example {
public:
static int count;
static void print() { /* 仅访问静态成员 */ }
};
int Example::count = 0;
3. 友元函数与友元类
- 友元函数/类可访问目标类的私有成员,但友元类不反向共享权限。
class FriendTarget {
private:
int secret;
friend class FriendClass;
friend void friend_func();
};
4. 构造函数类型
- 默认构造函数:无参数。
- explicit 构造函数:禁止隐式转换。
explicit String(int size); - 委托构造函数:通过初始化列表调用其他构造函数。
Example() : Example(0) {} - 移动构造函数:接管右值资源,标记为
noexcept。String(String&& other) noexcept : data(other.data) { other.data = nullptr; } - 拷贝构造函数:复制对象状态。
String(const String& other);
5. 移动语义与完美转发
完美转发:std::forward 保持参数原始值类别(左值/右值)。
template<typename T>
void wrapper(T&& arg) {
target(std::forward<T>(arg));
}
移动语义:std::move 将左值转为右值,避免拷贝开销。
std::vector<int> v1 = std::move(v2);
6. 函数对象(仿函数)
重载 operator() 使对象可调用:
struct Adder {
int operator()(int a, int b) {
return a + b;
}
};
Adder add;
add(1, 2);
7. 多重继承与菱形继承
- 菱形继承问题:派生类间接继承基类多次。
- 虚继承:通过
virtual关键字解决重复继承。
class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};
8. 虚函数
纯虚函数:定义接口,强制子类实现。
class Abstract {
public:
virtual void pure() = 0;
};
虚函数:运行时动态绑定,需通过指针/引用调用。
class Base {
public:
virtual void show() {
std::cout << "Base";
}
};
class Derived : public Base {
void show() override {
std::cout << "Derived";
}
};
Base* obj = new Derived();
obj->show();
9. new 与 malloc 对比
| 特性 | new (C++) | malloc (C) |
|---|---|---|
| 内存分配 | 调用构造函数 | 仅分配内存 |
| 返回类型 | 类型指针(T*) | void* |
| 失败处理 | 抛出 bad_alloc 异常 | 返回 nullptr |
| 示例 | int* p = new int(10); | int* p = (int*)malloc(sizeof(int)); |

