类内的约束
const 成员函数与常量对象
mutable 与逻辑常量性
static 数据成员与成员函数
类外的协作
友元函数、友元类
类作为模块:.h 与 .cpp
前置声明、命名空间、ODR
能够为一个类建立“只读接口 + 类级状态 + 模块边界”,并解释头文件为什么这样写。
const 成员函数:接口的只读承诺 class Target {
public:
bool is_built() const { return built_; }
int priority() const { return priority_; }
void build() { built_ = true; }
private:
int priority_ = 0;
bool built_ = false;
};
void print(const Target& t) {
t.is_built(); // OK
t.build(); // 编译错误
}
const 成员函数
凡是“查询”而非“修改”的成员函数,一律加 const。这是接口契约的一部分。
const 只约束“成员本身” class A {
public:
void f() const {
x_ = 10; // 错误:修改 int 成员
p_ = new char[20]; // 错误:修改指针本身
std::strcpy(p_, "AB"); // 编译通过!
}
private:
int x_ = 0;
char* p_ = nullptr;
};
const 成员函数保证:
不修改对象的直接成员
不改变指针的指向
但它不保证“指针指向的内容”不变。这是 const 的浅层语义。
如果成员是指针,且逻辑上不应修改其指向内容,应在接口层避免暴露可写路径;必要时用 const char* 或封装成只读视图。
class TargetList {
public:
Target& at(int i) {
return targets_[i];
}
const Target& at(int i) const {
return targets_[i];
}
private:
std::vector<Target> targets_;
};
TargetList list;
list.at(0).build(); // 非 const 版本
const TargetList& clist = list;
clist.at(0).build(); // 错误:const 版本
非 const 对象优先调用非 const 版本
const 对象只能调用 const 版本
两个版本通常返回引用,避免拷贝
标准库容器也采用这种设计:begin() / cbegin()、operator[] 的 const 重载。
mutable:逻辑常量性 class Target {
public:
bool is_built() const {
++query_count_; // 允许修改 mutable
return built_;
}
int query_count() const { return query_count_; }
private:
bool built_ = false;
mutable int query_count_ = 0;
};
缓存计算结果
统计查询次数
互斥量(mutable std::mutex)
mutable 表达“逻辑上不改变对象”,不是“绕过 const 检查”。把业务字段设为 mutable 会破坏接口承诺。
static 数据成员:属于类,不属于对象 class Target {
public:
Target() { ++count_; }
Target(const Target&) { ++count_; }
~Target() { --count_; }
static int count() { return count_; }
private:
static int count_; // 声明
};
int Target::count_ = 0; // 定义(C++17 之前)
所有对象共享同一份 count_
必须在类外定义并初始化(C++17 之前)
生命周期从程序开始到结束
可通过 Target::count() 访问,不需要对象
可以写 inline static int count_ = 0;,直接在类内定义,不需要类外定义。
this class Target {
public:
static int count() {
return count_;
// return id_; // 错误:没有 this
}
private:
int id_ = 0;
static int count_;
};
int n = Target::count(); // 不需要对象
Target t;
int m = t.count(); // 也可以通过对象调用
访问静态数据成员
调用其他静态成员函数
作为类级工具函数
访问非静态数据成员
使用 this
声明为 const(没有对象可 const)
class Target {
friend std::ostream& operator<<(std::ostream& os,
const Target& t);
friend class TargetList;
friend void Scheduler::dispatch(const Target&);
private:
int id_;
std::string name_;
};
友元是封装与效率之间的折中:不是成员,但被授权访问非 public 成员。应尽量少用,优先通过 public 接口完成。
不对称
class A {
friend class B; // B 可以访问 A
};
class B {
// 没有 friend class A;
};
B 是 A 的友元,不代表 A 是 B 的友元。
不传递
class A {
friend class B;
};
class B {
friend class C;
};
C 不是 A 的友元;友元关系不会沿链传播。
友元关系是单向、非传递的授权,必须显式声明。它也不是“类的成员”,不受继承影响。
<< class Target {
public:
Target(int id, std::string name)
: id_(id), name_(std::move(name)) {}
friend std::ostream& operator<<(std::ostream& os,
const Target& t);
private:
int id_;
std::string name_;
};
std::ostream& operator<<(std::ostream& os, const Target& t) {
return os << "[" << t.id_ << "] " << t.name_;
}
<< 的左操作数是 std::ostream,不能写成成员函数
需要访问 Target 的私有数据
返回 ostream& 支持链式输出
也可以提供 public 的 print(os) 成员函数,让 operator<< 调用它,从而避免友元。两种设计都常见。
从物理上对程序实体分组,可独立编写、编译、测试。
接口:供其他模块使用的声明
实现:具体的定义与算法
target.h:类定义、函数声明、常量
target.cpp:成员函数定义、静态成员定义
main.cpp:#include "target.h"
修改实现不需要重新编译 main.cpp(只重新链接),前提是接口不变。
#pragma once 传统写法:include guard
#ifndef TARGET_H
#define TARGET_H
class Target {
// ...
};
#endif
第一次包含时定义宏
再次包含时整段被跳过
现代写法:#pragma once
#pragma once
class Target {
// ...
};
编译器保证同一文件只包含一次
几乎所有主流编译器都支持
不是 ISO 标准,但事实标准
头文件保护解决的是“同一翻译单元重复包含”,不是“多个源文件各包含一次”。后者是正常的,声明可以重复,定义不行。
// Teacher.h
#pragma once
class Student; // 前向声明:只知道“有这样一个类”
class Teacher {
public:
void set_student(Student* s) { student_ = s; }
private:
Student* student_; // 指针:不需要完整定义
};
// Teacher.cpp
#include "Teacher.h"
#include "Student.h" // 真正使用 Student 的成员时才包含
成员是指针或引用
函数参数/返回值是指针或引用
不需要知道对象大小和成员
成员是对象本身(需要完整类型计算大小)
继承基类(需要完整定义)
调用成员函数/访问成员(需要声明)
// target.h
namespace minibuild {
class Target {
// ...
};
void print(const Target& t);
} // namespace minibuild
// main.cpp
#include "target.h"
int main() {
minibuild::Target t(1, "main.o", 2);
minibuild::print(t);
}
头文件中不要写 using namespace std;
源文件中可以有限使用,但更推荐显式限定
匿名命名空间用于文件内私有实体
C++17 支持嵌套命名空间简写 namespace a::b { }
在头文件写 using namespace std; 会污染所有包含它的源文件,可能引发名字冲突。
inline 单独编译,统一链接
g++ -std=c++17 -c target.cpp -o target.o
g++ -std=c++17 -c main.cpp -o main.o
g++ target.o main.o -o app
每个 .cpp 是一个翻译单元
头文件被复制进每个包含它的 .cpp
链接器负责合并符号
ODR(单一定义规则)
同一个函数/变量在程序中只能有一个定义
头文件中定义非 inline 函数 → 多个 .o 都有一份 → 链接错误
inline 函数/变量允许在多个翻译单元中定义(定义必须相同)
类定义、模板、constexpr 函数通常放在头文件
undefined reference to Target::Target(...):声明了但没链接实现;multiple definition of ...:头文件里写了非 inline 的函数定义。
Target 拆成模块 // target.h
#pragma once
#include <iosfwd>
#include <string>
class Target {
public:
Target(int id, std::string name, int priority);
~Target();
void build();
bool is_built() const;
int id() const;
static int count();
friend std::ostream& operator<<(std::ostream& os,
const Target& t);
private:
int id_;
std::string name_;
int priority_;
bool built_ = false;
static int count_;
};
#pragma once 防止重复包含
<iosfwd> 只前置声明 ostream,减少依赖
静态成员 count_ 在类内声明
operator<< 作为友元
析构函数负责计数减一
<iosfwd> 适合只需要引用 std::ostream& 的头文件;真正实现输出时在 .cpp 中包含 <ostream>。
target.cpp // target.cpp
#include "target.h"
#include <iostream>
#include <utility>
int Target::count_ = 0;
Target::Target(int id, std::string name, int priority)
: id_(id), name_(std::move(name)),
priority_(priority) {
++count_;
}
Target::~Target() { --count_; }
void Target::build() { built_ = true; }
bool Target::is_built() const { return built_; }
int Target::id() const { return id_; }
int Target::count() { return count_; }
std::ostream& operator<<(std::ostream& os, const Target& t) {
return os << "[" << t.id_ << "] " << t.name_
<< (t.built_ ? " built" : " todo");
}
静态成员在 .cpp 中定义
构造函数/析构函数维护 count_
友元函数可以访问 id_、name_、built_
operator<< 返回 os 支持链式输出
也可以写 inline static int count_ = 0;,省去类外定义。
Target 把 Target 拆成三个文件:
target.h:类定义、static int count()、友元 operator<<
target.cpp:构造函数、析构函数、成员函数、静态成员定义
main.cpp:创建 3 个 Target,打印 Target::count(),输出每个任务
要求:
#pragma once
count_ 记录存活对象数
operator<< 输出 [id] name todo/built
g++ target.cpp main.cpp -o app 编译
三个文件可以独立编译、统一链接
Target::count() 在创建/销毁后正确变化
std::cout << target 能输出正确格式
头文件中没有函数定义(inline 除外)
头文件中没有 using namespace std;
先在头文件写声明,再在源文件写定义;链接错误通常来自“声明了但没定义”或“头文件里定义了非 inline 函数”。
// target.h
#pragma once
#include <iosfwd>
#include <string>
class Target {
public:
Target(int id, std::string name, int priority);
~Target();
static int count();
friend std::ostream& operator<<(std::ostream& os,
const Target& t);
private:
int id_;
std::string name_;
int priority_;
bool built_ = false;
static int count_;
};
// target.cpp(节选)
#include "target.h"
#include <ostream>
#include <utility>
int Target::count_ = 0;
Target::Target(int id, std::string name, int priority)
: id_(id), name_(std::move(name)),
priority_(priority) {
++count_;
}
Target::~Target() { --count_; }
int Target::count() { return count_; }
std::ostream& operator<<(std::ostream& os, const Target& t) {
return os << "[" << t.id_ << "] " << t.name_;
}
完整版本见本章 code/ 目录。注意:operator<< 的定义放在 .cpp,头文件只留友元声明。
const / static
在 const 成员函数中修改成员
常量对象调用非 const 成员函数
静态成员只声明未定义 → 链接错误
静态成员函数访问非静态成员
用 mutable 掩盖设计问题
友元 / 模块
以为友元是成员
以为友元对称或可传递
头文件里写非 inline 函数定义 → 重复定义
头文件里 using namespace std;
前置声明后直接使用对象(需要完整类型)
循环包含却没有前置声明
编译错误看“类型/访问/声明”;链接错误看“定义/符号/库”。undefined reference 优先检查是否漏了 .cpp 或静态成员定义。
const 成员函数能修改指针成员指向的内容吗?为什么?
inline 函数定义不能放在头文件里?#pragma once 能解决这个问题吗?
只读承诺;常量对象只能调用 const 成员;mutable 仅用于逻辑常量性。
类级共享;静态成员函数没有 this;C++17 可 inline static。
.h 放声明,.cpp 放定义;#pragma once、前置声明、命名空间、ODR。
好的类设计:接口尽可能 const,状态尽可能私有,依赖尽可能少。