
🎬 博主名称 :键盘敲碎了雾霭
🔥 个人专栏 : 《C语言》《数据结构》 《C++》
⛺️指尖敲代码,雾霭皆可破

文章目录
- 一、默认成员函数
-
- [1.1 默认成员函数介绍](#1.1 默认成员函数介绍)
- [1.2 构造函数](#1.2 构造函数)
- [1.3 析构函数](#1.3 析构函数)
- [1.4 拷贝构造函数](#1.4 拷贝构造函数)
- [1.5 运算符重载](#1.5 运算符重载)
-
- [1.5.1 运算符重载](#1.5.1 运算符重载)
- [1.5.2 赋值运算符重载](#1.5.2 赋值运算符重载)
- [1.6 取地址运算符重载](#1.6 取地址运算符重载)
-
- [1.6.1 const成员函数](#1.6.1 const成员函数)
- [1.6.2 取地址运算符重载](#1.6.2 取地址运算符重载)
- 二、日期类实现
-
- [2.1 代码实现](#2.1 代码实现)
-
- [2.1.1 Date.h](#2.1.1 Date.h)
- [2.1.2 Date.cpp](#2.1.2 Date.cpp)
- [2.1.3 test.cpp](#2.1.3 test.cpp)
- [2.2 补充](#2.2 补充)
- 文章结语
一、默认成员函数
1.1 默认成员函数介绍
默认成员函数就是用户没有显式实现,编译器会自动生成的成员函数称为默认成员函数。一个类,我们不写的情况下编译器会默认生成以下6个默认成员函数,需要注意的是这6个中最重要的是前4个,最后两个取地址重载不重要。并且C++11以后还会增加两个默认成员函数,移动构造和移动赋值,通过本文学习,需要了解以下两个方面:
- 我们不写时,编译器默认生成的函数行为是什么,是否满足我们的需求。
- 编译器默认生成的函数不满足我们的需求,我们需要自己实现,那么如何自己实现?
1.2 构造函数
构造函数是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象 (我们常使用的局部对象是栈帧创建时,空间就开好了),而是对象实例化时初始化对象 。
以Date类为例,逐一讲解构造函数的特点:
cpp
#include<iostream>
using namespace std;
class Date
{
public:
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date a1;//定义的时候调用构造函数,构造函数在对象实例化时初始化对象
a1.Print();
return 0;
}
- 函数名与类名相同。
- 无返回值。(返回值啥都不需要给,也不需要写void,不要纠结,C++规定如此)
- 对象实例化时系统会自动调用对应的构造函数。
- 构造函数可以重载。
cpp
//无参调用构造函数
Date()
{
_year = 2026;
_month = 3;
_day = 21;
}
//有参
Date(int year,int month,int day)
{
_year = year;
_month = month;
_day = day;
}
//全缺省
Date(int year=1, int month=1, int day=1)
{
_year = year;
_month = month;
_day = day;
}
调用全缺省时,不需调用无参和有参,存在歧义,编译器不知道调用谁
- 如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成
- 无参构造函数 、全缺省构造函数 、我们不写构造时编译器默认生成的构造函数 ,都叫做默认构造函数。但是这三个函数有且只有一个存在,不能同时存在。无参构造函数和全缺省构造函数虽然构成函数重载,但是调用时会存在歧义 。要注意很多同学会认为默认构造函数是编译器默认生成那个叫默认构造,实际上无参构造函数、全缺省构造函数也是默认构造,总结一下就是不传实参就可以调用的构造就叫默认构造。(也可以叫做零实参构造)
补充:C++把类型分成内置类型(基本类型)和自定义类型。内置类型就是语言提供的原生数据类型,如:int/char/double/指针等,自定义类型就是我们使用class/struct等关键字自已定义的类型
- 我们不写,编译器默认生成的构造,对内置类型成员变量的初始化没有要求 ,也就是说是是否初始化是不确定的,看编译器。对于自定义类型成员变量,要求调用这个成员变量的默认构造函数初始化。如果这个成员变量,没有默认构造函数,那么就会报错,我们要初始化这个成员变量,需要用初始化列表才能解决。
总结:大多数情况下,构造函数需要我们自己去实现
少数情况下,可以不用实现,比如MyQueue,因为自定义成员变量会默认调用自己的默认函数
cpp
#include<iostream>
using namespace std;
typedef int STDatatype;
class Stack
{
public:
Stack(int n=4)
{
if (_capacity == _size)
{
STDatatype* ptr = (STDatatype*)malloc(sizeof(STDatatype)*n);
if (ptr == NULL)
{
perror("malloc");
return;
}
}
_capacity = n;
_size = 0;
}
private:
STDatatype* arr;
int _capacity;
int _size;
};
class MyQueue
{
public:
private:
Stack st1;
Stack st2;
};
int main()
{
MyQueue mq;
}
1.3 析构函数
析构函数与构造函数功能相反,析构函数不是完成对对象本身的销毁 ,比如局部对象是存在栈帧的,函数结束栈帧销毁,他就释放了,不需要我们管,C++规定对象在销毁时会自动调用析构函数,完成对象中资源的清理释放工作 。析构函数的功能类比我们之前Stack实现的Destroy功能,而像Date没有Destroy,其实就是没有资源需要释放,所以严格说Date是不需要析构函数的。
特点:
- 析构函数名是在类名前加上字符~
- 无参数无返回值(确定了一个类只能有一个析构函数)
- 若未显式定义,系统会自动生成默认的析构函数
- 对象生命周期结束时,系统会自动调用析构函数
以Stack为例(有资源释放)
cpp
#include<iostream>
using namespace std;
typedef int STDatatype;
class Stack
{
public:
Stack(int n=4)
{
if (_capacity == _size)
{
STDatatype* ptr = (STDatatype*)malloc(sizeof(STDatatype)*n);
if (ptr == NULL)
{
perror("malloc");
return;
}
}
_capacity = n;
_size = 0;
}
~Stack()
{
free(arr);
arr = nullptr;
_capacity = _size = 0;
}
private:
STDatatype* arr;
int _capacity;
int _size;
};
int main()
{
Stack st1;
return 0;
}
- 跟构造函数类似,我们不写编译器自动生成的析构函数对内置类型成员不做处理,自定类型成员会调用他的析构函数。(注意的是我们显示写析构函数,对于自定义类型成员也会调用他的析构,也就是说自定义类型成员无论什么情况都会自动调用析构函数。)
cpp
class MyQueue
{
public:
MyQueue()
{
_arr = (int *)malloc(sizeof(int) * 10);
}
~MyQueue()
{
free(_arr);
_arr = nullptr;
}
private:
Stack st1;
Stack st2;
int* _arr;
};
int main()
{
MyQueue q1;
return 0;
}
补充:当遇到多个类时,后定义的先析构(后进先出)
cpp
int main()
{
Stack st1;
Stack st2;
return 0;
}
C++比起C语言有了构造和析构,方便不少,有了this指针(不用传参)
以 leetcode一道题为例
20.有效的括号,题目描述:给定一个只包括'('、'{'、'['的字符串s,判断字符串是否有效。
- C语言
c
bool isValid(char* s)
{
Stack st;
STInit(&st);
while(*s)
{
if(*s=='('||*s=='{'||*s=='[')
{
STPush(&st,*s);
}
else
{
if(STEmpty(&st))
{
STDsetroy(&st);
return false;
}
char tmp =STTop(&st);
STPop(&st);
if((tmp=='('&&*s!=')')||(tmp=='{'&&*s!='}')||(tmp=='['&&*s!=']'))
{
return false;
}
}
s++;
}
if(STEmpty(&st))
{
STDsetroy(&st);
return true;
}
STDsetroy(&st);
return false;
}
- C++
cpp
class Solution
{
public:
bool isValid(char* s)
{
Stack st;
while (*s)
{
if (*s == '(' || *s == '{' || *s == '[')
{
st.Push(*s);
}
else
{
if (st.Empty())
{
return false;
}
char tmp = st.Top();
st.Pop();
if ((tmp == '(' && *s != ')') || (tmp == '{' && *s != '}') || (tmp == '[' && *s != ']'))
{
return false;
}
}
s++;
}
bool ret = st.Empty();
return ret;
}
};
1.4 拷贝构造函数
如果一个构造函数的第一个参数是自身类类型的引用,且任何额外的参数都有默认值 ,则此构造函数也叫做拷贝构造函数,也就是说拷贝构造是一个特殊的构造函数。用来初始化对象
特点:
- 拷贝构造函数是构造函数的一个重载
cpp
#include<iostream>
using namespace std;
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;
}
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2026, 3, 23);
d1.Print();
Date d2(d1);
d2.Print();
}
- 拷贝构造函数的第一个参数必须是类类型对象的引用,使用传值方式编译器直接报错,因为语法逻辑上会引发无穷递归调用。拷贝构造函数也可以多个参数,但是第一个参数必须是类类型对象的引用,后面的参数必须有缺省值。(C++规定传值会默认调用拷贝构造函数)
- C++规定自定义类型对象进行拷贝行为必须调用拷贝构造,所以这里自定义类型传值传参和传值返回都会调用拷贝构造完成。
- 若未显式定义拷贝构造,编译器会生成自动生成拷贝构造函数。自动生成的拷贝构造对内置类型成员变量会完成值拷贝/浅拷贝 (一个字节一个字节的拷贝),对自定义类型成员变量会调用他的拷贝构造。
- 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动生成的拷贝构造就可以完成需要的拷贝,所以不需要我们显示实现拷贝构造。
cpp
//Date(const Date&d)
//{
// _year = d._year;
// _month = d._month;
// _day = d._day;
//}
- 像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的拷贝构造完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。像MyQueue这样的类型内部主要是自定义类型Stack成员,编译器自动生成的拷贝构造会调用Stack的拷贝构造,也不需要我们显示实现MyQueue的拷贝构造。这里还有一个小技巧,如果一个类显示实现了析构并释放资源,那么他就需要显示写拷贝构造,否则就不需要 。(会重复析构,传值传参会改变外面(里面有指向的资源),自定义类型传值传参不好,用引用)
cpp
#include<iostream>
using namespace std;
typedef int STDatatype;
class Stack
{
public:
Stack(int n = 4)
{
if (_capacity == _size)
{
STDatatype* ptr = (STDatatype*)malloc(sizeof(STDatatype) * n);
if (ptr == NULL)
{
perror("malloc");
return;
}
arr = ptr;
}
_capacity = n;
_size = 0;
}
Stack(const Stack& st)
{
STDatatype *ptr= (STDatatype*)malloc(sizeof(STDatatype) * st._capacity);
if (ptr == NULL)
{
perror("malloc");
}
arr = ptr;
memcpy(arr, st.arr, sizeof(STDatatype) * st._size);
_capacity = st._capacity;
_size = st._size;
}
void Push(STDatatype x)
{
arr[_size++] = x;
}
~Stack()
{
free(arr);
arr = nullptr;
_capacity = _size = 0;
}
private:
STDatatype* arr;
int _capacity;
int _size;
};
int main()
{
Stack st;
st.Push(1);
st.Push(2);
st.Push(2);
st.Push(2);
Stack st1(st);
}
补充:另一种写法:
cpp
Stack st1=st2;
- 传值返回会产生一个临时对象调用拷贝构造,但是会拷贝两次,效率较低,传值引用返回,返回的是返回对象的别名(引 用),没有产生拷贝,传引用返回可以减少拷贝,但是一定要确保返回对象,在当前函数结束后还在,才能用引用返回。
传值返回
cpp
Stack Fuc()
{
Stack st1;
return st1;
}
传引用返回
cpp
Stack& Fuc()
{
static Stack st1;
return st1;
}
1.5 运算符重载
1.5.1 运算符重载
- 当运算符被用于类类型的对象时,C++语言允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应的运算符重载,则会编译报错。
- 运算符重载是具有特殊名字的函数,他的名字是由operator和后面要定义的运算符共同构成。和其他函数一样,它也具有其返回类型和参数列表以及函数体。
- 重载运算符函数的参数个数和该运算符作用的运算对象数量一样多。一元运算符有一个参数,二元运算符有两个参数,二元运算符的左侧运算对象传给第一个参数,右侧运算对象传给第二个参数
- 如果一个重载运算符函数是成员函数,则它的第一个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数比运算对象少一个。
cpp
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year=1,int month=1,int day=1)
{
_year = year;
_month = month;
_day = day;
}
bool operator==(Date d2)
{
return _year == d2._year && _month == d2._month && _day == d2._day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2026, 3, 23);
Date d2(2026, 3, 23);
d1.operator==( d2);
d1 == d2;
}
- 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持一致
- 不能通过连接语法中没有的符号来创建新的操作符:比如operator@。
.*、::、sizeof、?:注意以上5个运算符不能重载
cpp
class A
{
public:
void fuc()
{
cout << "A::fuc" << endl;
}
};
typedef void (A::*PF)() ;
int main()
{
PF pf = nullptr;
pf = &A::fuc;//C++规定成员函数需要加&才能取地址
A a;
(a.*pf)();//不能直接调用函数,因为有隐藏的this指针,实参和形参也不能直接显示
return 0;
}
- 重载操作符至少有一个类类型参数,不能通过运算符重载改变内置类型对象的含义
- 一个类需要重载哪些运算符,是看哪些运算符重载后有意义,比如Date类重载operator-就有意义,但是重载operator+就没有意义。
- 重载++运算符时,有前置++和后置++ ,运算符重载函数名都是operator++,无法很好的区分。C++规定,后置++重载时,增加一个int形参,跟前置++构成函数重载,方便区分。
1.5.2 赋值运算符重载
*赋值运算符重载是一个默认成员函数,用于完成两个已经存在的对象直接的拷贝赋值,这里要注意跟拷贝构造区分,拷贝构造用于一个对象拷贝初始化给另一个要创建的对象。
cpp
class Date
{
public:
Date(int year,int month,int day)
{
_year = year;
_month = month;
_day = day;
}
Date(Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
void operator=(Date d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2016, 3, 5);
Date d2(2017, 5, 4);
d1 = d2;
Date d3(d1);
Date d4 = d1;
return 0;
}
- 有返回值,且建议写成当前类类型引用,引用返回可以提高效率,有返回值目的是为了支持连续赋值场景。
cpp
Date& operator=(Date d)
{
_year = d._year;
_month = d._month;
_day = d._day;
return (*this);
}
cpp
d1=d2=d3;
- 没有显式实现时,编译器会自动生成一个默认赋值运算符重载,默认赋值运算符重载行为跟默认拷贝构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(一个字节一个字节的拷贝),对自定义类型成员变量会调用他的赋值重载函数
- 这里还有一个小技巧,如果一个类显示实现了析构并释放资源,那么他就需要显示写赋值运算符重载和拷贝构造,否则就不需要。
1.6 取地址运算符重载
1.6.1 const成员函数
- 将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后面。
- const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改 。
const修饰Date类的Print成员函数,Print隐含的this指针由Date *const this变成const Date*const this,在Date实现中构造、+=赋值重载由于要改变成员变量,后面不需要加const修饰
1.6.2 取地址运算符重载
- 取为普通取地址运算符重载和const取地址运算符重载,一般这两个函数编译器自动生成的就可以够我们用了,不需要去显示实现。除非一些很特殊的场景,比如我们不想让别人取到当前对象的地址
cpp
Date& operator&()
{
return *this;
}
const Date& operator&()const
{
return *this;
}
二、日期类实现
因为为Date类是内置类型,构造函数需要自己实现,析构、拷贝构造、赋值重载不需要,会默认自己实现,需要注意返回值,传引用返回,需要判断类是否存在,逻辑之间为了方便可以相互调用
2.1 代码实现
2.1.1 Date.h
cpp
#pragma once
#include<iostream>
#include<stdbool.h>
using namespace std;
class Date
{
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);
public:
bool Check();
Date(int year=1,int month=1,int day=1)
{
_year = year;
_month = month;
_day = day;
if (!Check())
{
cout << "非法日期:";
Print();
}
}
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
int GetMonthDay(int year, int month)
{
static int day[] = { 0,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 day[month];
}
bool operator<(const Date& d);
bool operator<=(const Date& d);
bool operator==(const Date& d);
bool operator>(const Date& d);
bool operator>=(const Date& d);
bool operator!=(const Date& d);
Date operator+(int day);
Date& operator+=(int day);
Date operator-(int day);
Date& operator-=(int day);
Date& operator++();
Date operator++(int);
Date& operator--();
Date operator--(int);
int operator-(const Date& d);
private:
int _year;
int _month;
int _day;
};
2.1.2 Date.cpp
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include"Date.h"
Date Date::operator+(int day)
{
Date tmp = *this;
tmp += day;
return tmp;
}
Date& Date::operator+=(int day)
{
if (day < 0)
{
*this -= (-day);
return *this;
}
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month++;
if (_month == 13)
{
_month = 1;
_year++;
}
}
return *this;
}
Date Date::operator-(int day)
{
Date tmp = *this;
tmp -= day;
return tmp;
}
Date& Date::operator-=(int day)
{
if (day < 0)
{
*this += (-day);
return *this;
}
_day -= day;
while (_day <= 0)
{
_month--;
if (_month == 0)
{
_month = 12;
_year--;
}
_day += GetMonthDay(_year, _month);
}
return *this;
}
bool Date::operator<(const Date& d)
{
if (_year < d._year)
{
return true;
}
else if(_year==d._year)
{
if (_month < d._month)
{
return true;
}
else if (_month == d._month)
{
return _day < d._day;
}
}
return false;
}
bool Date:: operator<=(const Date& d)
{
return *this < d || *this == d;
}
bool Date::operator==(const Date& d)
{
return _year == d._year && _month == d._month && _day == d._day;
}
bool Date::operator>(const Date& d)
{
return !(*this <= d);
}
bool Date::operator>=(const Date& d)
{
return !(*this < d);
}
bool Date::operator!=(const Date& d)
{
return !(*this == d);
}
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;
}
bool Date::Check()
{
if (_month > 0 && (_day > 0 && _day <= GetMonthDay(_year, _month)))
{
return true;
}
else
{
return false;
}
}
int Date::operator-(const Date& d)
{
int flag = 1;
Date max = *this;
Date min = d;
if (*this < d)
{
max = d;
min = *this;
flag = -1;
}
int n = 0;
while (min < max)
{
min++;
n++;
}
return n*flag;
}
ostream& operator<<(ostream& out, const Date& d)
{
out << d._year << "年" << d._month << "月" << d._day <<"日" << endl;
return out;
}
istream& operator>>(istream& in, Date& d)
{
while (1)
{
cout << "请输入年月日>:";
in >> d._year >> d._month >> d._day;
if (!d.Check())
{
cout << "输入日期非法>:" ;
d.Print();
cout << "请重新输入"<<endl;
}
else
{
break;
}
}
return in;
}
2.1.3 test.cpp
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include"Date.h"
int main()
{
//Date d1(2026, 3, 24);
//Date d2(2027, 2, 31);
//cout << d1<<d2;
Date d1;
Date d2;
cin >> d1 >> d2;
cout << d1 << d2;
cout << d1 - d2 << endl;
return 0;
}
2.2 补充
operator-可以复用operator-=,相反也可以倒过来,但是优先operator-复用operator-=,比起后者多了两次拷贝构造和一次赋值重载
cpp
Date Date::operator-(int day)
{
Date tmp = *this;
tmp -= day;
return tmp;
}
Date& Date::operator-=(int day)
{
_day -= day;
while (_day <= 0)
{
_month--;
if (_month == 0)
{
_month = 12;
_year--;
}
_day += GetMonthDay(_year, _month);
}
return *this;
}
cpp
Date Date::operator-(int day)
{
Date tmp = *this;
tmp._day -= day;
while (tmp._day <= 0)
{
tmp._month--;
if (tmp._month == 0)
{
tmp._month = 12;
tmp._year--;
}
tmp._day += GetMonthDay(tmp._year, tmp._month);
}
return tmp;
}
Date& Date::operator-=(int day)
{
*this = *this - day;
return *this;
}
文章结语
感谢你读到这里~我是「键盘敲碎了雾霭」,愿这篇文字帮你敲开了技术里的小迷雾 💻
如果内容对你有一点点帮助,不妨给个暖心三连吧👇
👍 点赞 | ❤️ 收藏 | ⭐ 关注
(听说三连的小伙伴,代码一次编译过,bug绕着走~)
你的支持,就是我继续敲碎技术雾霭的最大动力 🚀
🐶 小彩蛋:
/^ ^\
/ 0 0 \
V\ Y /V
/ - \
/ |
V__) ||
摸一摸毛茸茸的小狗,赶走所有疲惫和bug~我们下篇见 ✨