自定义类型与类
C++ 的面向对象从这篇开始:struct 怎么从 C 的「数据包」进化成 C++ 的「类型」、enum class 解决了什么问题、union 在 C++11 里解开了什么限制、类的六个默认成员函数各自负责什么、拷贝控制五法则为什么一个都不能少。所有内容都从「不用它会出什么事」的角度讲。
一、结构体
1.1 C struct vs C++ struct
C 的 struct 只是数据的打包,不能有函数;C++ 的 struct 是完整的类:
struct Point {
double x = 0.0; // 类内初始值(C++11)
double y = 0.0;
double distance_to(const Point& other) const; // 成员函数
static Point origin() { return Point{0.0, 0.0}; } // 静态成员
};struct 和 class 在 C++ 里几乎完全等价,唯一区别是默认访问权限:struct 默认 public,class 默认 private。惯例:纯数据聚合用 struct,有不变式(invariant)要维护的用 class。
1.2 初始化
Point p1; // OK:x/y 有类内初始值,全是 0
Point p2{1.0, 2.0}; // 聚合初始化
Point p3 = {3.0, 4.0}; // 同上(拷贝列表初始化)
Point arr[3]{{1,1}, {2,2}}; // 第三个元素 {0,0}C++17 起聚合初始化可以给基类初始化,派生类也可以是聚合类:
struct Base { int a; };
struct Derived : Base { int b; };
Derived d{{1}, 2}; // C++17:d.a=1, d.b=2聚合初始化的隐患:指定初始化器(C++20)之前的版本按位置初始化,结构体中间插入一个成员,所有 {...} 初始化点的含义全部错位——大项目里改头文件导致几十处初始化悄悄错值的经典事故。C++20 指定初始化器解决了一半:
Point p{.x = 1.0, .y = 2.0}; // C++20:按名字,加成员不影响这里1.3 位域
硬件寄存器、协议报文用位域压缩存储:
struct Color {
unsigned r : 5; // r 占 5 位,0~31
unsigned g : 6;
unsigned b : 5;
}; // 总共 16 位
Color c;
c.r = 31; // OK
// c.r = 32; // 溢出:存进去变成 0(窄化,不报错)位域的坑:不能取地址(&c.r 非法)、不能用于多线程原子操作、跨编译器布局可能不同(大端/小端、打包规则)。二进制协议解析别用位域,用移位和掩码手工组装。
1.4 sizeof 与对齐
struct A { char c; int i; }; // sizeof 是 8,不是 5!结构体有内存对齐:每个成员放在自己对齐要求的整数倍地址上,整体大小是最大对齐的倍数。char(1) + int(4):c 后面补 3 字节,i 从偏移 4 开始,总 8。优化布局的准则:成员按对齐要求从大到小排列(int 在前,char 在后),能省 padding。alignas 可以强制更大对齐,alignof 查询对齐值。
二、联合(union)
union 的成员共享同一块内存,大小是最大成员(加对齐):
union Value {
int i;
float f;
char bytes[4];
};
Value v;
v.i = 0x3F800000; // IEEE 754 的 1.0f
// v.f 现在是 1.0——同一块内存的不同解释用途:类型双关(type punning,协议解析)、节省内存(互斥状态)。坑:
- 同一时刻只有一个成员「活跃」,读非活跃成员是 UB(C++11 起,读共同初始序列除外)。
- 含构造函数/析构函数的成员时,C++11 允许但需要自己手动管理生命周期——placement new 构造、显式调析构:
union U {
std::string s;
std::vector<int> v;
U() {} // 什么都不构造
~U() {} // 什么都不析构
};
U u;
new (&u.s) std::string("hello"); // 构造 s
u.s.~basic_string(); // 手动析构- 匿名 union 直接暴露成员:
struct Token {
enum Kind { kInt, kFloat } kind;
union { // 匿名 union
int int_val;
float float_val;
};
};
Token t{kInt};
t.int_val = 42; // 直接访问,没有中间名字这类「tagged union」用 C++17 的 std::variant 更安全(自动管理生命周期、std::visit 分发)。
三、枚举
3.1 传统 enum
enum Color { kRed, kGreen, kBlue }; // 0, 1, 2
enum Status { kOk = 200, kNotFound = 404, kError = 500 };问题一箩筐:枚举值隐式转 int(kRed + 1 == kGreen 没人拦)、不同枚举之间可比较(Color::kRed == Status::kOk 编译通过)、枚举名泄露到外层作用域(两个枚举不能有同名项)。
3.2 enum class(C++11,推荐)
enum class Color { kRed, kGreen, kBlue }; // 必须写 Color::kRed
enum class Status : uint8_t { kOk, kError }; // 指定底层类型
Color c = Color::kRed;
// int i = c; // 错误:不隐式转 int
int i = static_cast<int>(c); // 显式转换,0
// c == 1 // 错误:不能和数字比
c == Color::kRed // OK强类型枚举的三个改进:不隐式转整型、必须作用域限定、可指定底层类型(省内存、保证 ABI 兼容)。
3.3 使用模式
enum class Op { kAdd, kSub, kMul, kCount };
// 用数组/函数代替 switch 分派
const char* kOpNames[] = {"+", "-", "*"};
static_assert(sizeof(kOpNames) / sizeof(kOpNames[0]) ==
static_cast<size_t>(Op::kCount), "名字要齐");
// switch 要覆盖所有枚举值,编译器能检查完整性(配合 -Wswitch)
switch (op) {
case Op::kAdd: return a + b;
case Op::kSub: return a - b;
case Op::kMul: return a * b;
case Op::kCount: break; // 或者 default:
}四、类与对象
4.1 定义与访问控制
class Stack {
public: // 对外接口
void push(int v);
int pop();
bool empty() const { return size_ == 0; }
int size() const { return size_; }
private: // 内部实现,外部不可见
static constexpr int kCapacity = 100; // C++11:类内初始化
int data_[kCapacity];
int size_ = 0;
};public 是接口,private 是实现,protected 给派生类用的中间层。封装的价值不在「防黑客」而在「约束」:私有成员让你可以随意改实现,只要公开接口不变,调用方代码不用动。数据成员一律 private,公开的只有行为。
4.2 this 指针
成员函数有一个隐藏参数 this,指向调用对象:
bool Stack::empty() const {
return this->size_ == 0; // 和 size_ == 0 等价,this 隐式传递
}const 成员函数里的 this 是 const Stack*,不能改成员(mutable 除外)。非 const 对象调用 const 函数 OK,反过来不行。
4.3 对象的创建与生命周期
Stack s1; // 栈上:作用域结束自动析构
Stack s2{1, 2}; // 列表初始化(需要对应构造函数)
Stack* s3 = new Stack; // 堆上:必须手动 delete
Stack* s4 = new Stack[10]; // 对象数组
delete s4; // 错误!数组要 delete[]
delete[] s4; // 正确五、构造函数
5.1 形式与初始化列表
class Person {
public:
Person() : name_("unknown"), age_(0) {} // 默认构造
Person(const std::string& name, int age)
: name_(name), age_(age) {} // 带参构造
Person(std::istream& is); // 声明在别处定义
private:
std::string name_;
int age_;
const int kId_; // const 成员
int& ref_; // 引用成员
};初始化列表不是可选的:const 成员、引用成员、没有默认构造的基类/成员,只能在初始化列表里初始化。赋值做不到——赋值前它们已经被「默认初始化」过了。
class Widget {
public:
Widget(int n) { size_ = n; } // 差:size_ 先被默认构造/不初始化,再赋值
Widget(int n) : size_(n) {} // 好:直接构造
};Widget 的 size_ 若是 std::string,第一种写法多一次默认构造 + 赋值,白白浪费。
5.2 初始化顺序
成员按声明顺序初始化,不是初始化列表里的书写顺序:
class Foo {
public:
Foo(int n) : b_(n), a_(b_) {} // 危险!a_ 先于 b_ 初始化,此时 b_ 是垃圾
private:
int a_;
int b_;
};GCC/Clang 会警告(-Wreorder)。写初始化列表时刻意按声明顺序排,避免依赖。
5.3 explicit 与单参数构造
class MyInt {
public:
MyInt(int v) : v_(v) {}
private:
int v_;
};
void f(MyInt m);
f(42); // 编译通过!int 隐式转 MyInt——多数时候不是你要的
f(MyInt{42}); // 显式,清晰
class MyInt {
public:
explicit MyInt(int v) : v_(v) {} // 禁止隐式转换
};
// f(42); // 编译错误,必须 f(MyInt{42})单参数构造函数(含除第一个外都有默认值的多参构造)一律加 explicit,除非你就是想要隐式转换(如 std::string 接受 const char*)。
5.4 委托构造与继承构造
C++11 起一个构造函数可以调用另一个,避免重复:
class Date {
public:
Date(int y, int m, int d) : y_(y), m_(m), d_(d) {}
Date(int y, int m) : Date(y, m, 1) {} // 委托:日默认 1
Date() : Date(1970, 1, 1) {} // 委托到三参版
};5.5 =default 与 =delete
class NonCopyable {
public:
NonCopyable() = default; // 用编译器生成的版本
NonCopyable(const NonCopyable&) = delete; // 禁用拷贝
NonCopyable& operator=(const NonCopyable&) = delete;
};=delete 比「声明成 private 且不实现」更干净——它在重载决议阶段就把调用排除,错误信息更友好。
六、析构函数
~Stack() { /* 释放资源 */ }析构函数在对象生命终点自动调用:栈对象离开作用域、堆对象被 delete、临时量生命周期结束。名字固定为 ~类名,无参数无返回值,不能重载。
析构函数只做一件事:释放构造函数获取的资源——堆内存、文件句柄、锁、网络连接。这就是 RAII(资源获取即初始化):资源的生命周期绑定对象,对象在,资源在;对象亡,资源收。
class FileHandle {
public:
explicit FileHandle(const char* path) : f_(std::fopen(path, "r")) {}
~FileHandle() { if (f_) std::fclose(f_); } // 保证关闭,哪怕中途抛异常
private:
std::FILE* f_;
};
{
FileHandle f("data.txt");
// ... 哪怕这里抛异常,f 的析构照样执行,文件不会泄漏句柄
}七、拷贝控制:五法则
编译器为类生成六个特殊成员:默认构造、析构、拷贝构造、拷贝赋值、移动构造、移动赋值。管理资源的类必须显式管理拷贝与移动——这是 C++ 与 GC 语言的分水岭。
class Buffer {
public:
Buffer(size_t n) : data_(new int[n]{}), size_(n) {}
~Buffer() { delete[] data_; } // 1. 析构
Buffer(const Buffer& other) // 2. 拷贝构造:深拷贝
: data_(new int[other.size_]), size_(other.size_) {
std::copy(other.data_, other.data_ + size_, data_);
}
Buffer& operator=(const Buffer& other) { // 3. 拷贝赋值
if (this != &other) {
int* new_data = new int[other.size_]; // 先分配(异常安全)
std::copy(other.data_, other.data_ + other.size_, new_data);
delete[] data_;
data_ = new_data;
size_ = other.size_;
}
return *this;
}
Buffer(Buffer&& other) noexcept // 4. 移动构造:偷资源
: data_(other.data_), size_(other.size_) {
other.data_ = nullptr;
other.size_ = 0;
}
Buffer& operator=(Buffer&& other) noexcept { // 5. 移动赋值
if (this != &other) {
delete[] data_;
data_ = other.data_;
size_ = other.size_;
other.data_ = nullptr;
other.size_ = 0;
}
return *this;
}
private:
int* data_;
size_t size_;
};五法则的实践形式(C++11 起):
- 需要自定义析构 → 几乎一定也需要自定义拷贝(默认拷贝是浅拷贝,会 double free)。
- 有了正确的拷贝,再补上移动(
noexcept)性能更佳。 - 都不要?编译器生成的默认版本就是对的——不写就是最好的优化,让编译器干活(Rule of Zero:用智能指针/容器成员,自己一个特殊成员都不用写)。
浅拷贝的后果用图说话:
Buffer a(100);
Buffer b = a; // 编译器默认拷贝:b.data_ = a.data_(同一个指针!)
// 析构时 a 和 b 都 delete[] data_ → double free,程序崩溃八、静态成员
静态成员属于类而不是对象,所有对象共享一份:
class Counter {
public:
Counter() { ++count_; }
static int count() { return count_; } // 静态成员函数:没有 this
private:
static int count_; // 声明
};
int Counter::count_ = 0; // 定义(.cpp 里,只此一份)
Counter a, b, c;
Counter::count(); // 3,不需要对象,直接类名调用要点:
- 静态成员函数没有
this指针,只能访问静态成员。它是普通函数,可以取地址传给 C API。 - C++11 前非
const整型静态成员可以类内初始化(static const int kMax = 100;),其他类型必须在类外定义。C++17 起inline static统一解决:inline static int count_ = 0;头文件里直接定义,无 ODR 问题。 - 静态成员的生命周期从程序启动到结束(构造时机:首次经过定义点时)。
九、友元
友元把私有成员的访问权授予指定的函数或类:
class Matrix {
public:
Matrix(int r, int c) : rows_(r), cols_(c), data_(r * c) {}
private:
int rows_, cols_;
std::vector<double> data_;
friend std::ostream& operator<<(std::ostream&, const Matrix&); // 友元函数
friend class MatrixTest; // 友元类
};
std::ostream& operator<<(std::ostream& os, const Matrix& m) {
// 可以访问 m.rows_ / m.cols_ / m.data_
return os;
}什么时候必须用:operator<</operator>>(左操作数是流,不能是成员)、对称运算符需要访问两边私有成员、两个类紧密协作(如迭代器与容器)。
友元是封装的漏洞,不是增强。能不用就不用——优先提供公开的访问接口(如 rows()、at(r, c))。测试类做友元是可以接受的工程妥协。
十、const 成员函数与 mutable
class Sensor {
public:
double value() const { return value_; } // const 函数:承诺不改对象
void refresh() { value_ = read_hardware(); }
private:
double value_;
mutable uint64_t cached_hash_ = 0; // 逻辑上不属于对象状态
mutable bool hash_valid_ = false;
uint64_t hash() const {
if (!hash_valid_) { // const 函数里可以改 mutable 成员
cached_hash_ = compute();
hash_valid_ = true;
}
return cached_hash_;
}
};const 成员函数是接口契约:「调用我不会改变你看到的状态」。mutable 用于缓存、引用计数、互斥量这类「物理可变但逻辑不变」的成员——std::mutex 就是靠 mutable 让自己能在 const 成员函数里加锁。
相关阅读
- 《继承、多态与接口》—— 类的下一章
- 《异常处理与内存管理》—— RAII 与智能指针
- 《C++ 实战:手写类与经典案例》—— 综合运用
