高级程序设计(C++)


const、static、友元与类作为模块

计算机学院    杨已彪

yangyibiao@nju.edu.cn

本讲提纲

类内的约束

  • 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();     // 编译错误
}
两个作用
  1. 编译器禁止在函数内修改数据成员
  2. 常量对象/常量引用只能调用 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() 访问,不需要对象

C++17

可以写 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_;
};
三种友元
  1. 全局函数
  2. 另一个类(其所有成员函数)
  3. 另一个类的某个成员函数
定位

友元是封装与效率之间的折中:不是成员,但被授权访问非 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<< 调用它,从而避免友元。两种设计都常见。


类作为模块:接口与实现

模块

从物理上对程序实体分组,可独立编写、编译、测试。

  • 接口:供其他模块使用的声明

  • 实现:具体的定义与算法

C++ 的类模块
  • target.h:类定义、函数声明、常量

  • target.cpp:成员函数定义、静态成员定义

  • main.cpp:#include "target.h"

target.h 接口:声明 target.cpp 实现:定义 main.cpp 使用接口 #include

修改实现不需要重新编译 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; 会污染所有包含它的源文件,可能引发名字冲突。


编译与链接:ODR 与 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 支持链式输出

C++17

也可以写 inline static int count_ = 0;,省去类外定义。


课堂任务 6:模块化 Target

任务

把 Target 拆成三个文件:

  • target.h:类定义、static int count()、友元 operator<<

  • target.cpp:构造函数、析构函数、成员函数、静态成员定义

  • main.cpp:创建 3 个 Target,打印 Target::count(),输出每个任务

要求:

  1. 使用 #pragma once
  2. 静态成员 count_ 记录存活对象数
  3. operator<< 输出 [id] name todo/built
  4. 用 g++ target.cpp main.cpp -o app 编译
验收标准
  • 三个文件可以独立编译、统一链接

  • Target::count() 在创建/销毁后正确变化

  • std::cout << target 能输出正确格式

  • 头文件中没有函数定义(inline 除外)

  • 头文件中没有 using namespace std;

提示

先在头文件写声明,再在源文件写定义;链接错误通常来自“声明了但没定义”或“头文件里定义了非 inline 函数”。


任务 6 参考实现(关键片段)

// 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 或静态成员定义。


课堂小测

  1. const 成员函数能修改指针成员指向的内容吗?为什么?
  2. 静态数据成员与普通数据成员的生命周期、存储位置、共享方式有什么不同?
  3. 友元关系是否对称?是否传递?请各举一个反例。
  4. 为什么非 inline 函数定义不能放在头文件里?#pragma once 能解决这个问题吗?

小结:接口稳、类级状态清、模块边界明

const

只读承诺;常量对象只能调用 const 成员;mutable 仅用于逻辑常量性。

static

类级共享;静态成员函数没有 this;C++17 可 inline static。

模块

.h 放声明,.cpp 放定义;#pragma once、前置声明、命名空间、ODR。

好的类设计:接口尽可能 const,状态尽可能私有,依赖尽可能少。




未完待续