上一讲里的 Stack 要手动调 Init 和 Destroy,漏一次就是泄漏或者空指针。C++ 把这四次调用交给编译器:对象创建时自动构造,销毁时自动析构,拷贝时自动拷贝,赋值时自动赋值。这四类函数连同两个取地址重载一共六个,不写时编译器会生成,写的时候要按固定签名来。
六个默认成员函数,编译器替你写还是你写

- 构造函数:对象实例化时做初始化。
- 析构函数:对象生命周期结束时清理资源。
- 拷贝构造:用同类对象初始化一个正在创建的对象。
- 赋值重载:把已有对象的值赋给另一个已经存在的对象。
- 普通取地址重载、const 取地址重载:
&对象时调用。
C++11 起又多两个:移动构造与移动赋值,那是后面的内容。
两类问题决定了要不要自己写:不写时编译器生成的行为能否满足需求;不能满足时,正确的实现长什么样。
构造函数:默认构造有三种写法,只能留一种
构造函数的名字和类名相同,没有返回值(连 void 都不写),对象创建时由系统自动调用。它不负责开空间——局部对象的空间在栈帧建立时就分配好了——它负责的是初始化对象的内容,替代以前手写的 Init。
规则集中在一起:
- 函数名与类名相同。
- 无返回值。
- 对象实例化时自动调用。
- 可以重载。
- 不写时编译器生成一个无参的默认构造;一旦自己写了任意一个构造函数,编译器就不再生成。
- 无参构造、全缺省构造、编译器生成的构造,三者都叫默认构造函数。它们只能存在一个,因为无参构造和全缺省构造虽然构成重载,但无参调用时两条路径都成立,编译器报歧义。
- 编译器生成的默认构造对内置类型成员不保证初始化,值是不确定的;对自定义类型成员要求它有默认构造,没有就报 C2512。
第 6 条容易记反:默认构造不等于“编译器生成的那个”,只要不传实参就能调用,它就算默认构造。
#include <iostream>
class Date
{
public:
Date()
{
_year = 1;
_month = 1;
_day = 1;
}
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
std::cout << _year << '-' << _month << '-' << _day << '\n';
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
Date d2(2025, 1, 1);
// Date d3(); // 这是函数声明,不是创建对象
d1.Print();
d2.Print();
return 0;
}Date d3(); 这一行编译器按函数声明解析:返回 Date、名为 d3、无参。想创建一个用默认构造的对象,写 Date d3;。
把无参构造注释掉、只留下带参版本,Date d1; 就会报 C2512(没有合适的默认构造函数可用)。
自定义类型成员的情况:
#include <cstdio>
#include <cstdlib>
#include <cstddef>
class Stack
{
public:
Stack(int n = 4)
{
_a = (int*)malloc(sizeof(int) * n);
if (_a == nullptr)
{
std::perror("malloc fail");
return;
}
_capacity = n;
_top = 0;
}
private:
int* _a;
std::size_t _capacity;
std::size_t _top;
};
class MyQueue
{
private:
Stack _pushst;
Stack _popst;
};
int main()
{
MyQueue mq;
return 0;
}MyQueue 一个构造函数都没写,编译器生成的默认构造会去调用两个 Stack 成员的默认构造。Stack(int n = 4) 是全缺省构造,属于默认构造,所以这一步成立;如果 Stack 只写 Stack(int n),MyQueue 这一段就编不过。这也解释了为什么“默认构造”这个定义值得记准。
析构函数:只负责清理,不负责销毁
析构函数在对象生命周期结束时自动调用,做的是资源释放。局部对象的空间本来就随栈帧回收,析构函数管的是对象持有的堆内存、文件句柄这类东西。
特点:
- 名字是类名前加
~。 - 无参数、无返回值,也不写
void。 - 一个类只能有一个析构函数;不写时编译器自动生成。
- 对象生命周期结束时系统自动调用。
- 编译器生成的析构对内置类型成员不做任何事,对自定义类型成员会调用它自己的析构。
- 自己写的析构,同样会对自定义类型成员调用它们的析构。
- 没有资源要释放可以不写(Date),默认生成的够用也可以不写(MyQueue),有资源申请就必须自己写(Stack),否则泄漏。
- 同一个作用域里多个对象,后定义的先析构。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstddef>
class Stack
{
public:
Stack(int n = 4)
{
_a = (int*)malloc(sizeof(int) * n);
_capacity = n;
_top = 0;
}
~Stack()
{
std::cout << "~Stack()" << '\n';
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
void Push(int x)
{
if (_top == _capacity)
{
int newcapacity = _capacity == 0 ? 4 : _capacity * 2;
int* tmp = (int*)realloc(_a, newcapacity * sizeof(int));
if (tmp == nullptr)
{
std::perror("realloc fail");
return;
}
_a = tmp;
_capacity = newcapacity;
}
_a[_top++] = x;
}
void Pop()
{
assert(_top > 0);
--_top;
}
bool Empty() const
{
return _top == 0;
}
int Top() const
{
assert(_top > 0);
return _a[_top - 1];
}
private:
int* _a;
std::size_t _capacity;
std::size_t _top;
};
class MyQueue
{
private:
Stack _pushst;
Stack _popst;
};
int main()
{
Stack st;
MyQueue mq;
return 0;
}mq 比 st 后定义,所以先析构 mq。MyQueue 没写析构,编译器生成的那份会依次调用 _popst 和 _pushst 的析构(成员按声明的逆序销毁),两段 ~Stack() 输出先出现。手写 ~MyQueue(){} 也拦不住这两个成员的析构,自定义类型成员在任何情况下都会走自己的析构。
自动析构的价值在提前返回的代码里最明显。括号匹配:
bool isValid(const char* s)
{
Stack st;
while (*s)
{
if (*s == '[' || *s == '(' || *s == '{')
{
st.Push(*s);
}
else
{
if (st.Empty())
return false;
char top = st.Top();
st.Pop();
if ((*s == ']' && top != '[')
|| (*s == '}' && top != '{')
|| (*s == ')' && top != '('))
{
return false;
}
}
++s;
}
return st.Empty();
}函数里有两个提前 return false,两处都不需要释放栈。C 版本每个提前返回点都要先 STDestroy(&st):
if (STEmpty(&st))
{
STDestroy(&st);
return false;
}漏一个分支就是内存泄漏。构造函数和析构函数把这件事从“记得写”变成了“编译器保证”。
拷贝构造:第一个参数为什么必须是引用
拷贝构造函数是这样一个构造函数:第一个参数是自身类类型的引用,其余参数都有默认值。
- 它本身是构造函数,与其它构造函数构成重载。
- 第一个参数必须是类类型对象的引用。写成传值,编译器直接报 C2652,因为语法上会无穷递归。
- 自定义类型对象发生拷贝时必须调用拷贝构造:传值传参、传值返回都会调用。
- 不写时编译器生成一份:内置类型成员逐字节拷贝(浅拷贝),自定义类型成员调用它自己的拷贝构造。
- Date 这种全是内置类型且不持有资源的类不用写;Stack 持有堆资源必须写深拷贝;MyQueue 内部是两个 Stack,编译器生成的拷贝会调用 Stack 的拷贝构造,也不用写。经验规则是:自己写了析构并释放资源,就要写拷贝构造。
- 不省略时,传值返回会构造一个临时对象并调用拷贝构造;传引用返回不产生拷贝,但返回局部对象的引用会悬空。
为什么第一个参数不能传值:

#include <iostream>
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// Date(Date d) // 错:error C2652,非法的复制构造函数,第一个参数不应是 Date
Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
Date(Date* d) // 普通构造函数,不是拷贝构造
{
_year = d->_year;
_month = d->_month;
_day = d->_day;
}
void Print() const
{
std::cout << _year << '-' << _month << '-' << _day << '\n';
}
private:
int _year;
int _month;
int _day;
};
void Func1(Date d)
{
std::cout << &d << '\n';
d.Print();
}
int main()
{
Date d1(2024, 7, 5);
Func1(d1); // 传值传参,调用拷贝构造,形参是新对象
Date d2(&d1); // 走 Date(Date*),普通构造
Date d3(d1); // 拷贝构造
Date d4 = d1; // 也是拷贝构造,不是赋值
std::cout << &d1 << '\n';
return 0;
}Func1(d1) 里打印的 &d 和 main 里打印的 &d1 是两个地址,说明形参是新创建的对象,拷贝构造被调用了一次。
Date d2(&d1) 常被误认成拷贝,实际调用的是 Date(Date*) 这个普通构造函数,参数是指针。只有用同类对象初始化,才叫拷贝构造。
Date d4 = d1 虽然长得像赋值,但 d4 此刻还不存在,它仍然是“用 d1 初始化一个新对象”,所以是拷贝构造。
Stack 持有资源时必须深拷贝:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstddef>
typedef int STDataType;
class Stack
{
public:
Stack(int n = 4)
{
_a = (STDataType*)malloc(sizeof(STDataType) * n);
_capacity = n;
_top = 0;
}
Stack(const Stack& st)
{
_a = (STDataType*)malloc(sizeof(STDataType) * st._capacity);
if (_a == nullptr)
{
std::perror("malloc fail");
return;
}
std::memcpy(_a, st._a, sizeof(STDataType) * st._top);
_top = st._top;
_capacity = st._capacity;
}
~Stack()
{
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
private:
STDataType* _a;
std::size_t _capacity;
std::size_t _top;
};
int main()
{
Stack st1;
Stack st2 = st1; // 没有深拷贝时,两个对象的 _a 指向同一块内存
return 0;
}不写拷贝构造,编译器生成的那份只把 _a 这个指针值复制过去。st1 和 st2 的 _a 指向同一块堆内存,两个对象析构时 free 同一块地址两次,程序在第二次析构时崩溃。深拷贝的做法是重新申请一块同样大的内存,再把有效元素搬过去;_capacity 一并复制,_top 决定搬多少个元素。
传引用返回省掉拷贝,但返回局部对象的引用是悬空引用:
Date& Func2()
{
Date tmp(2024, 7, 5);
return tmp; // tmp 随函数结束销毁,返回的引用指向已释放的栈空间
}Date ret = Func2(); 会拿这个悬空引用去拷贝,读到的内容已经不确定。传引用返回只在返回对象活过函数结束时才成立。
运算符重载:哪些能重载、怎么命名
类类型对象遇到运算符时,C++ 会把它转成调用对应的运算符重载函数;没有对应函数就编译报错。重载函数的名字由 operator 加运算符构成,有返回类型、参数表和函数体。
- 参数个数与该运算符作用的运算对象数量一致。二元运算符有两个参数,左操作数给第一个,右操作数给第二个。
- 重载成成员函数时,第一个运算对象由隐式的
this接走,参数比运算对象少一个。 - 重载不改变优先级和结合性。
- 不能拼出语言里没有的符号,
operator@不存在。 - 有五个运算符不能重载:
.*、::、sizeof、?:、.。 - 至少有一个参数是类类型,不能借重载改内置类型的行为:
// int operator+(int x, int y) { return x - y; } // 错:operator+ 必须至少有一个类类型形参- 按需重载。Date 重载
operator-有意义(两个日期相减得天数),重载operator+没有意义。 - 前置
++和后置++的函数名都是operator++,C++ 用参数区分:后置版本多一个int形参,调用时编译器传 0 进去,这个参数本身用不到。 <<和>>重载成全局函数。重载成成员函数时this占掉第一个参数位,调用会变成对象 << cout,不符合书写习惯。
#include <iostream>
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
bool operator==(const Date& d) const
{
return _year == d._year && _month == d._month && _day == d._day;
}
void Print() const
{
std::cout << _year << '-' << _month << '-' << _day << '\n';
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 7, 5);
Date d2(2024, 7, 6);
d1.operator==(d2); // 显式调用成员版本
d1 == d2; // 编译器转换成 d1.operator==(d2)
return 0;
}如果比较逻辑需要同时拿到两个对象的私有成员,也可以写成全局函数,在类里用 friend 声明:bool operator==(const Date& d1, const Date& d2);,调用形式是 operator==(d1, d2),d1 == d2 由编译器转换成这个调用。全局版和成员版不要同时保留,两份都可用时 d1 == d2 直接报歧义。
成员函数指针的写法也顺带记一下,.* 属于不能重载的那五个之一:
#include <iostream>
class A
{
public:
void func()
{
std::cout << "A::func()" << '\n';
}
};
typedef void (A::*PF)();
int main()
{
PF pf = &A::func; // 成员函数要加 & 才能取到函数指针
A obj;
(obj.*pf)(); // 对象调成员函数指针用 .*
return 0;
}赋值重载与日期类
赋值运算符重载完成的是两个已经存在的对象之间的赋值,和拷贝构造的区别只在对象是否已经存在:
Date d4 = d1; // d4 还不存在:拷贝构造
d4 = d1; // d4 已经存在:赋值重载特点:
- 必须重载成成员函数,不能写成全局函数。
- 参数建议写
const 当前类类型&,传值会多一次拷贝。 - 返回值建议写当前类类型的引用,支持连续赋值
a = b = c;返回*this是因为d1 = d2这个表达式的值就是d1。 - 不写时编译器生成一份,行为和默认拷贝构造类似:内置类型成员逐字节拷贝,自定义类型成员调它自己的赋值重载。
- Date 不用写;Stack 持有资源要自己写深拷贝;MyQueue 内部是 Stack,会自动调用 Stack 的赋值,不用写。和拷贝构造一样,写了析构释放资源就该写赋值。
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
Date(const Date& d)
: _year(d._year), _month(d._month), _day(d._day)
{}
Date& operator=(const Date& d)
{
if (this != &d) // 自赋值时直接跳过拷贝
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
private:
int _year;
int _month;
int _day;
};课件这段代码上方的注释写的是“不要检查自己给自己赋值的情况”,和代码里 if (this != &d) 正好相反,是注释写反了。自赋值判断在这里不是必需的,但省掉一次无意义的拷贝,对持有资源的类还能避免先把资源释放再读自己。
日期类把前一讲的运算符重载落到实际类型上:
#pragma once
#include <iostream>
#include <cassert>
class Date
{
friend std::ostream& operator<<(std::ostream& out, const Date& d);
friend std::istream& operator>>(std::istream& in, Date& d);
public:
Date(int year = 1900, int month = 1, int day = 1);
void Print() const;
int GetMonthDay(int year, int month) const
{
assert(month > 0 && month < 13);
static int monthDayArray[13] = {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
return 29;
return monthDayArray[month];
}
bool CheckDate() const;
bool operator<(const Date& d) const;
bool operator<=(const Date& d) const;
bool operator>(const Date& d) const;
bool operator>=(const Date& d) const;
bool operator==(const Date& d) const;
bool operator!=(const Date& d) const;
Date& operator+=(int day);
Date operator+(int day) const;
Date& operator-=(int day);
Date operator-(int day) const;
int operator-(const Date& d) const;
Date& operator++();
Date operator++(int);
Date& operator--();
Date operator--(int);
private:
int _year;
int _month;
int _day;
};
std::ostream& operator<<(std::ostream& out, const Date& d);
std::istream& operator>>(std::istream& in, Date& d);GetMonthDay 里的闰年判断必须写成上面这样,内层括号不能省。课件写的是
if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))&& 的优先级高于 ||,这句实际被解析成 (month == 2 && (year % 4 == 0 && year % 100 != 0)) || (year % 400 == 0)。结果是 2000 年、2400 年这类整百年份,不管查几月都返回 29 天,2000-01-05 会被算成 1 月有 29 天,日期加减整体错位。加上 month == 2 之后的外层括号就能修好。
实现部分:
#include "Date.h"
Date::Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
if (!CheckDate())
std::cout << "日期非法" << '\n';
}
bool Date::CheckDate() const
{
return _month >= 1 && _month <= 12
&& _day >= 1 && _day <= GetMonthDay(_year, _month);
}
void Date::Print() const
{
std::cout << _year << '-' << _month << '-' << _day << '\n';
}
bool Date::operator<(const Date& d) const
{
if (_year != d._year)
return _year < d._year;
if (_month != d._month)
return _month < d._month;
return _day < d._day;
}
bool Date::operator<=(const Date& d) const
{
return *this < d || *this == d;
}
bool Date::operator>(const Date& d) const
{
return !(*this <= d);
}
bool Date::operator>=(const Date& d) const
{
return !(*this < d);
}
bool Date::operator==(const Date& d) const
{
return _year == d._year && _month == d._month && _day == d._day;
}
bool Date::operator!=(const Date& d) const
{
return !(*this == d);
}
Date& Date::operator+=(int day)
{
if (day < 0)
return *this -= -day;
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
++_month;
if (_month == 13)
{
++_year;
_month = 1;
}
}
return *this;
}
Date Date::operator+(int day) const
{
Date tmp = *this;
tmp += day;
return tmp;
}
Date& Date::operator-=(int day)
{
if (day < 0)
return *this += -day;
_day -= day;
while (_day <= 0)
{
--_month;
if (_month == 0)
{
_month = 12;
--_year;
}
_day += GetMonthDay(_year, _month);
}
return *this;
}
Date Date::operator-(int day) const
{
Date tmp = *this;
tmp -= day;
return tmp;
}
int Date::operator-(const Date& d) const
{
Date max = *this;
Date min = d;
int flag = 1;
if (*this < d)
{
max = d;
min = *this;
flag = -1;
}
int n = 0;
while (min != max)
{
++min;
++n;
}
return n * flag;
}
Date& Date::operator++()
{
*this += 1;
return *this;
}
Date Date::operator++(int)
{
Date tmp(*this);
*this += 1;
return tmp;
}
Date& Date::operator--()
{
*this -= 1;
return *this;
}
Date Date::operator--(int)
{
Date tmp(*this);
*this -= 1;
return tmp;
}
std::ostream& operator<<(std::ostream& out, const Date& d)
{
out << d._year << '-' << d._month << '-' << d._day;
return out;
}
std::istream& operator>>(std::istream& in, Date& d)
{
in >> d._year >> d._month >> d._day;
if (!d.CheckDate())
std::cout << "日期非法" << '\n';
return in;
}两个工厂函数 operator+ 和 operator- 都复用 +=、-=,返回类型是值,因为结果是一个新的日期对象。operator+= 返回引用,支持 d1 += 1 之后继续链式操作。
课件的后置 ++ 示例里写的是 Date tmp;,那样返回的是默认构造出来的日期,不是自增前的值。后置版本必须先拷贝当前状态再自增,所以是 Date tmp(*this);。
构造函数允许 Date d = 1900; 这种隐式转换,因为默认参数让单参数调用成立。不需要这种隐式行为时,在构造函数前加 explicit。
const 成员函数与取地址重载
const 修饰成员函数时写在参数表后面:
void Print() const;它修饰的是隐式的 this 指针。原来的类型是 Date* const this,加 const 之后变成 const Date* const this:指向的对象也不能改了,所以这个函数里不能给任何成员赋值。
#include <iostream>
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print() const
{
std::cout << _year << '-' << _month << '-' << _day << '\n';
}
Date& operator+=(int day)
{
_day += day;
return *this;
}
Date* operator&()
{
return this;
}
const Date* operator&() const
{
return this;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 7, 5);
d1.Print(); // 非 const 对象调 const 成员函数:权限缩小,合法
const Date d2(2024, 8, 5);
d2.Print(); // const 对象只能调 const 成员函数
// d2 += 100; // 错:const 对象不能调非 const 成员函数
return 0;
}const 对象只能调用 const 成员函数,普通对象两个都能调。这和上一讲引用的规矩是同一条:权限可以缩小,不能放大。
取地址重载有普通版和 const 版,编译器自动生成的版本直接返回 this,够用。只有需要隐藏对象真实地址时才自己实现,比如返回 nullptr 让别人拿不到:
Date* operator&()
{
return this; // 也可以 return nullptr;
}这类需求极少,正常的类不要动它。
还没有评论 — 第一条由你来留。