结构体与类
类型设计是 C++ 最强大的能力之一。本节从最基础的 struct 和 class 开始,逐步建立现代 C++ 类型设计的核心概念:聚合初始化、构造函数、封装、枚举,以及良好的类设计原则。
struct 与 class:唯一的区别
在 C++ 中,struct 和 class 在语言层面几乎完全相同。它们唯一的区别是默认访问级别:
struct Point {
double x; // 默认 public
double y; // 默认 public
};
class Circle {
double radius; // 默认 private
public:
double area() const { return 3.14159 * radius * radius; }
};
何时用 struct,何时用 class?
struct:纯数据聚合,所有成员都是 public,没有不变量需要维护。例如坐标点、配置参数、DTO。
class:有不变量(invariants)需要保护的抽象。例如"半径必须为正数"、"容量永远大于等于大小"。
这是一个约定,不是语法强制——但整个 C++ 社区都遵守它。
聚合初始化(Aggregate Initialization)
当一个类型是聚合(aggregate)时,可以直接用花括号按成员顺序初始化,无需编写构造函数:
struct Point {
double x;
double y;
};
Point p1{3.0, 4.0}; // 聚合初始化
Point p2{}; // x=0.0, y=0.0(值初始化)
Point p3{1.0}; // x=1.0, y=0.0(后续成员值初始化)
聚合的条件
一个类型要成为聚合,必须满足:
- 没有 private 或 protected 非静态数据成员
- 没有用户声明的构造函数(C++20 起,允许用户
= delete的构造函数) - 没有虚函数
- 没有虚基类、private/protected 基类
指定初始化器(Designated Initializers,C++20)
C++20 引入了指定初始化器,允许按名称指定成员,顺序必须与声明顺序一致:
struct Config {
int width = 800;
int height = 600;
bool fullscreen = false;
int fps_limit = 60;
};
// 只修改需要的字段,其余用默认值
Config cfg{.width = 1920, .height = 1080, .fullscreen = true};
// cfg.fps_limit == 60(使用默认值)
指定初始化器的优势
对比 Config{1920, 1080, true, 60},指定初始化器让代码自文档化——读者不需要翻头文件就能理解每个参数的含义。当结构体有很多成员或多个同类型成员时,这尤为有价值。
带默认值的聚合
类内默认成员初始化器(NSDMI)与聚合初始化配合良好:
struct Rect {
double width = 1.0;
double height = 1.0;
std::string label = "unnamed";
};
Rect r1{}; // 全部使用默认值
Rect r2{.width = 10.0}; // 只覆盖 width
Rect r3{5.0, 3.0}; // 覆盖 width 和 height,label 用默认值
构造函数
当类型有不变量需要维护时,就需要构造函数来确保对象一创建就处于有效状态。
默认构造函数与参数化构造函数
class Circle {
public:
Circle() = default; // 显式请求编译器生成的默认构造函数
Circle(double r) : radius_{r} {
if (r <= 0) throw std::invalid_argument{"半径必须为正数"};
}
double area() const { return std::numbers::pi * radius_ * radius_; }
private:
double radius_ = 1.0; // NSDMI:默认构造时半径为 1.0
};
成员初始化列表
成员初始化列表在构造函数体执行之前初始化成员,这比在函数体中赋值更高效:
class Rect {
public:
// 推荐:成员初始化列表
Rect(double w, double h) : width_{w}, height_{h} {}
// 不推荐:函数体中赋值(对非平凡类型会多一次默认构造 + 赋值)
// Rect(double w, double h) {
// width_ = w; // 先默认构造,再赋值
// height_ = h;
// }
private:
double width_;
double height_;
};
初始化列表的顺序
成员的初始化顺序由声明顺序决定,而非初始化列表中的书写顺序。如果写反了顺序,编译器会警告(启用 -Wmember-init-order)。始终让初始化列表的顺序与声明顺序一致。
委托构造函数
一个构造函数可以调用同类的另一个构造函数,避免重复初始化逻辑:
class Connection {
public:
Connection(std::string host, int port, bool use_tls)
: host_{std::move(host)}, port_{port}, use_tls_{use_tls}
{
validate();
connect();
}
// 委托到完整版本,提供默认端口和 TLS
Connection(std::string host)
: Connection{std::move(host), 443, true} {}
private:
void validate();
void connect();
std::string host_;
int port_;
bool use_tls_;
};
explicit 关键字
单参数构造函数(或可以只传一个参数调用的构造函数)默认允许隐式转换,这通常不是你想要的:
class Meter {
public:
Meter(double value) : value_{value} {} // 隐式转换!
double get() const { return value_; }
private:
double value_;
};
void print_length(Meter m) {
std::println("{}m", m.get());
}
print_length(3.14); // 编译通过!double 隐式转换为 Meter
// 这真的是调用者想要的吗?
class Meter {
public:
explicit Meter(double value) : value_{value} {} // 阻止隐式转换
double get() const { return value_; }
private:
double value_;
};
print_length(3.14); // 编译错误!
print_length(Meter{3.14}); // OK,显式构造
经验法则
除非你刻意设计隐式转换(如 std::string 从 const char*),否则所有单参数构造函数都应该加 explicit。C++26 社区甚至在讨论"默认 explicit"的提案。
封装与访问控制
C++ 提供三个访问级别来控制成员的可见性:
| 关键字 | 谁能访问 | 典型用途 |
|---|---|---|
public | 任何代码 | 类的公开接口 |
private | 仅类自身和友元 | 实现细节、不变量维护 |
protected | 类自身、友元、派生类 | 为继承设计的扩展点(慎用) |
Getter/Setter 模式
当成员有不变量需要维护时,getter/setter 是合理的:
class Temperature {
public:
explicit Temperature(double celsius) : celsius_{celsius} {
if (celsius < -273.15) throw std::invalid_argument{"低于绝对零度"};
}
double celsius() const { return celsius_; }
double fahrenheit() const { return celsius_ * 9.0/5.0 + 32.0; }
void set_celsius(double c) {
if (c < -273.15) throw std::invalid_argument{"低于绝对零度"};
celsius_ = c;
}
private:
double celsius_;
};
何时不要使用 getter/setter
如果成员没有不变量,所有值都合法,那就直接用 struct:
// 反模式:无意义的 getter/setter
class BadPoint {
public:
double get_x() const { return x_; }
void set_x(double x) { x_ = x; }
double get_y() const { return y_; }
void set_y(double y) { y_ = y; }
private:
double x_, y_;
};
// 正确做法:直接用 struct
struct Point {
double x;
double y;
};
判断标准
问自己:"是否存在某些成员值的组合是非法的?"如果是,用 class + 封装来维护不变量。如果所有组合都合法,用 struct 即可。不要为了"面向对象"而套壳子。
enum class(强类型枚举)
C++11 引入的 enum class 解决了传统 enum 的两大问题:名称泄露到外围作用域,以及隐式转换为整数。
// 老式 enum(问题多)
enum Color { Red, Green, Blue }; // Red/Green/Blue 泄露到外围
int x = Red; // 隐式转换为 int,值为 0
// 现代 enum class(推荐)
enum class Color { Red, Green, Blue };
// int x = Color::Red; // 编译错误!不能隐式转为 int
int x = static_cast<int>(Color::Red); // 必须显式转换
指定底层类型
可以指定枚举的底层存储类型,控制大小和取值范围:
enum class HttpStatus : uint16_t {
OK = 200,
NotFound = 404,
ServerError = 500,
};
enum class Flags : uint8_t {
None = 0,
Readable = 1,
Writable = 2,
Exec = 4,
};
using enum(C++20)
在 switch 语句中,反复写 Color:: 前缀很冗长。C++20 的 using enum 在局部作用域引入枚举值:
std::string_view to_string(Color c) {
using enum Color; // 在本函数作用域内引入所有枚举值
switch (c) {
case Red: return "red";
case Green: return "green";
case Blue: return "blue";
}
std::unreachable(); // C++23:标记不可达
}
枚举与 switch 的配合
编译器会检查 switch 是否覆盖了 enum class 的所有枚举值。如果以后新增一个 Color::Yellow,所有未更新的 switch 都会触发 -Wswitch 警告——这是免费的安全保障。
成员函数
const 成员函数
标记为 const 的成员函数承诺不修改对象状态,可以被 const 对象调用:
class Vec2 {
public:
Vec2(double x, double y) : x_{x}, y_{y} {}
// const 成员函数:不修改对象,可以被 const Vec2 调用
double length() const {
return std::sqrt(x_ * x_ + y_ * y_);
}
// 非 const 成员函数:会修改对象
void normalize() {
double len = length();
x_ /= len;
y_ /= len;
}
private:
double x_, y_;
};
const Vec2 direction{3.0, 4.0};
direction.length(); // OK
// direction.normalize(); // 编译错误!不能对 const 对象调用非 const 方法
const 正确性
所有不修改对象逻辑状态的成员函数都应标记为 const。这不仅是文档,更是编译器强制的契约。养成"先标 const,需要修改时再去掉"的习惯。
static 成员与函数
static 成员属于类本身而非某个对象实例,常用于工厂函数和类级别的配置:
class Logger {
public:
// 工厂函数:根据不同需求创建实例
static Logger to_file(const std::string& path);
static Logger to_console();
void log(std::string_view msg);
private:
// static 数据成员:所有 Logger 实例共享
static inline int instance_count_ = 0;
explicit Logger(/* ... */);
};
this 指针
this 是指向当前对象的隐式指针。通常不需要显式使用,但在链式调用(fluent API)中很有用:
class QueryBuilder {
public:
QueryBuilder& select(std::string_view cols) {
query_ += std::format("SELECT {} ", cols);
return *this;
}
QueryBuilder& from(std::string_view table) {
query_ += std::format("FROM {} ", table);
return *this;
}
QueryBuilder& where(std::string_view cond) {
query_ += std::format("WHERE {}", cond);
return *this;
}
std::string build() const { return query_; }
private:
std::string query_;
};
// 链式调用
auto sql = QueryBuilder{}
.select("name, age")
.from("users")
.where("age > 18")
.build();
现代类设计原则
优先选择值语义
值语义意味着对象像 int 一样:拷贝产生独立副本,没有共享状态、没有悬挂指针。优先设计值类型,除非你有明确的理由需要引用语义。
// 值语义:每个变量是独立的
Vec2 a{1.0, 2.0};
Vec2 b = a; // b 是 a 的副本
b.normalize(); // 不影响 a
保持类小而专注
一个类应该只做一件事。如果你的类有 20 个成员函数,它很可能承担了太多职责。
// 反模式:God Object
class Application {
void init_window();
void load_config();
void run_game_loop();
void render_ui();
void save_highscore();
void play_audio();
// ... 50 个方法
};
// 推荐:职责分离
class Window { /* 窗口管理 */ };
class Config { /* 配置加载 */ };
class Renderer { /* 渲染 */ };
class AudioEngine { /* 音频 */ };
Rule of Zero(零法则)预览
如果你的类不直接管理资源(内存、文件句柄、网络连接等),就不要声明任何特殊成员函数(析构函数、拷贝/移动构造、拷贝/移动赋值):
// Rule of Zero:让编译器自动生成所有特殊成员函数
class Person {
public:
Person(std::string name, int age)
: name_{std::move(name)}, age_{age} {}
// 不需要写 ~Person()
// 不需要写拷贝构造/赋值
// 不需要写移动构造/赋值
// 编译器生成的版本完全正确!
private:
std::string name_; // string 自己管理内存
int age_;
};
为什么零法则有效?
当类的每个成员都是"自管理"类型(std::string、std::vector、std::unique_ptr 等),编译器生成的析构/拷贝/移动函数会逐成员调用对应操作,完全正确。我们将在第 3-7 节深入讨论特殊成员函数和"五法则"。
综合示例
把以上知识组合到一个完整的小例子中:
#include <cmath>
#include <format>
#include <iostream>
#include <numbers>
#include <string>
#include <string_view>
// 聚合:纯数据,无不变量
struct Point {
double x = 0.0;
double y = 0.0;
};
// 强类型枚举
enum class ShapeKind : uint8_t { Circle, Rectangle };
// 类:有不变量(半径 > 0,宽高 > 0)
class Shape {
public:
// 工厂函数
static Shape circle(Point center, double radius) {
if (radius <= 0) throw std::invalid_argument{"半径必须为正"};
Shape s;
s.kind_ = ShapeKind::Circle;
s.center_ = center;
s.dim1_ = radius;
return s;
}
static Shape rectangle(Point center, double w, double h) {
if (w <= 0 || h <= 0) throw std::invalid_argument{"宽高必须为正"};
Shape s;
s.kind_ = ShapeKind::Rectangle;
s.center_ = center;
s.dim1_ = w;
s.dim2_ = h;
return s;
}
// const 成员函数
double area() const {
using enum ShapeKind;
switch (kind_) {
case Circle: return std::numbers::pi * dim1_ * dim1_;
case Rectangle: return dim1_ * dim2_;
}
std::unreachable();
}
ShapeKind kind() const { return kind_; }
Point center() const { return center_; }
private:
Shape() = default; // 私有默认构造,强制通过工厂创建
ShapeKind kind_ = ShapeKind::Circle;
Point center_;
double dim1_ = 0.0; // circle: radius; rect: width
double dim2_ = 0.0; // rect: height
};
int main() {
auto c = Shape::circle(Point{.x = 1.0, .y = 2.0}, 5.0);
auto r = Shape::rectangle({.x = 0, .y = 0}, 3.0, 4.0);
std::println("圆面积: {:.2f}", c.area()); // 78.54
std::println("矩形面积: {:.2f}", r.area()); // 12.00
}
本章小结
struct与class唯一区别是默认访问级别;约定:数据聚合用 struct,有不变量的抽象用 class- 聚合初始化和 C++20 指定初始化器让纯数据类型的创建简洁且安全
- 成员初始化列表优于函数体赋值;单参数构造函数加
explicit - 封装是为了维护不变量——如果没有不变量,就别封装
enum class取代旧式enum:作用域限定 + 无隐式转换- 所有不修改状态的成员函数标记
const - 遵循 Rule of Zero:不管理资源就不要声明特殊成员函数