目录
3. 用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。
1.类的6个默认成员函数
如果一个类中什么成员都没有,简称为空类。空类中真的什么都没有吗?并不是,任何类在什么都不写时,编译器会自动生成以下 6 个默认成员函数。默认成员函数:用户没有显式实现,编译器会生成的成员函数称为默认成员函数。
接下来我们就来看看这6个默认成员函数吧!
2. 构造函数
2.1 概念
我们以Data类为例子:
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
d1.Init(2022, 12, 23);
d1.Print();
Date d2;
d2.Init(2022, 12, 24);
d2.Print();
return 0;
}
构造函数 是一个 特殊的成员函数,名字与类名相同 , 创建类类型对象时由编译器自动调用 ,以保证 每个数据成员都有 一个合适的初始值,并且 在对象整个生命周期内只调用一次 。
2.2 特性
构造函数 是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务 并不是开空间创建对象,而是 初始化对象 。
其特征如下:
1. 函数名与类名相同。2. 无返回值。3. 对象实例化时编译器 自动调用 对应的构造函数。4. 构造函数可以重载。
我们可以来试试:
Date()
{
_year = 0;
_month = 1;
_day = 1;
cout << "Date()" << endl;
}
我们运行一下程序:
初始化结果与我们预期的一样,那我们还能不能初始化对带有参数呀?
当然可以的:
Date(int year,int month,int day)
{
_year = year;
_month = month;
_day = day;
cout << "Date(int year,int month,int day)" << endl;
}
这种定义方式与第一种方式之间构成了函数重载,但是还有一种更简单的写法,能整合到一起,就是用缺省参数:
Date(int year=0, int month=1, int day=1)
{
_year = year;
_month = month;
_day = day;
cout << "Date(int year,int month,int day)" << endl;
}
但是这里有一个小问题,将加了缺省值的构造函数与第一种构造函数同时存在会发生什么?
Date()
{
_year = 0;
_month = 1;
_day = 1;
cout << "Date()" << endl;
}
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
cout << "Date(int year,int month,int day)" << endl;
}
我们发现他们是构成函数重载的,但是当定义一个Date类的对象时如果不带参数就会出问题,因为编译器不知道到底调用哪一个函数,这一点大家要注意。
5. 如果类中没有显式定义构造函数,则 C++ 编译器会自动生成一个 无参 的默认构造函数,一旦用户显式定义编译器将不再生成。
在上面,我们自己定义了构造函数,所以编译器并不会主动生成默认的构造函数,接下来再来思考一个问题:只定义上面带有缺省值的构造函数,用下面这种方法调用会有什么问题?
class Date
{
public:
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
cout << "Date(int year,int month,int day)" << endl;
}
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d6();
return 0;
}
我们编译一下,发现能够编过,但是当我们想用d6调用里面的成员方法时却报错了:
为什么呢?
解答: C++ 把类型分成内置类型 ( 基本类型 ) 和自定义类型。内置类型就是语言提供的数据类型,如: int/char... ,自定义类型就是我们使用 class/struct/union 等自己定义的类型,看看下面的程序,就会发现编译器生成默认的构造函数会对自定类型成员 _t 调用的它的默认成员函数。
class Time
{
public:
Time()
{
cout << "Time()" << endl;
_hour = 0;
_minute = 0;
_second = 0;
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
private:
// 基本类型(内置类型)
int _year;
int _month;
int _day;
// 自定义类型
Time _t;
};
int main()
{
Date d;
return 0;
}
我们调试起来看看:
7. 无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。 注意: 无参构造函数 、 全缺省构造函数 、 我们没写编译器默认生成的构造函数 ,都可以认为 是默认构造函数。
class Date
{
public:
Date()
{
_year = 1900;
_month = 1;
_day = 1;
}
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
这个上面我们有提到过,现在就不多提了。
讲了这么多,其实编译器生成默认的构造函数会对自定义类型成员调用的它的默认成员函数的好处是啥,大家还记得我们之前用栈实现队列吗?(忘记的可以参考这篇博客栈和队列)
我们来看看用C++实现给出的参考模板:
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
}
int pop() {
}
int peek() {
}
bool empty() {
}
};
有了默认析构函数后我们发现第一个好像加不加好像都已经无关紧要了,因为系统会默认生成一个,来看看下面的代码:(有关接口的实现我这里没有写,想要知道的可以参考上面我所写的栈与队列的博客,上面有解析和源码)
class Stack
{
private:
int* _a;
int _top;
int _capacity;
public:
Stack(int capacity = 4)
{
_a = (int*)malloc(sizeof(int) * capacity);
if (!_a)
{
perror("malloc fail\n");
exit(-1);
}
_top = 0;
_capacity = capacity;
}
};
class MyQueue {
public:
void push(int x) {
}
MyQueue() {
}
int pop() {
}
int peek() {
}
bool empty() {
}
private:
Stack pushSt;
Stack popSt;
};
int main()
{
MyQueue mq;
return 0;
}
我们调试起来就可以看见很明显初始化成功了的。
那初始化顺序是啥呢?
int main()
{
MyQueue mq;
Stack s1;
Stack s2(20);
return 0;
}
通过调试我们能够很快推出是先初始化s1,然后再初始化s2的。
3.析构函数
3.1 概念
通过前面构造函数的学习,我们知道一个对象是怎么来的,那一个对象又是怎么没呢的?析构函数:与构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由编译器完成的。而 对象在销毁时会自动调用析构函数,完成对象中资源的清理工作 。
像上面实现的Date类,我们并不需要自己实现一个析构函数,系统自己默认生成的就够用了(因为不需要手动释放资源,像在堆区申请的空间)但是Stack类就需要手动释放了,这个时候就得自己实现。
3.2 特性
析构函数是特殊的成员函数,其特征如下:
1. 析构函数名是在类名前加上字符 ~ 。2. 无参数无返回值类型。3. 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。注意:析构函数不能重载 。4. 对象生命周期结束时, C++ 编译系统系统自动调用析构函数。
这个看上去是不是与构造函数优点相似呀,没错,这个与构造函数绝大部分都类似,只有一小部分细节不一样,我们来试试:
~Stack()
{
free(_a);
_a = nullptr;
_top = 0;
_capacity = 0;
}
主函数中:
int main()
{
MyQueue mq;
Stack s1;
Stack s2(20);
return 0;
}
但是这里有一点与析构不同,就是是先销毁的s1,再销毁的s2吗?
我们知道初始化是顺序进行的,但是销毁释放空间却是逆序的,是先释放s2,再释放s1的,这一点大家务必要分清。
我们再来看一个题:
//设已经有A,B,C,D4个类的定义,程序中A,B,C,D析构函数调用顺序为?( )
C c;
int main()
{
A a;
B b;
static D d;
return 0;
}
我们可以自己写一个构造函数和析构函数来打印着看看:
不难发现:析构时会优先销毁局部变量(逆序),然后再销毁全局(逆序)。
4. 拷贝构造函数
4.1 概念
在现实生活中,可能存在一个与你一样的自己,我们称其为双胞胎。
拷贝构造函数 : 只有单个形参 ,该形参是对本 类类型对象的引用 ( 一般常用 const 修饰 ) ,在用 已存 在的类类型对象创建新对象时由编译器自动调用 。
4.2 特征
拷贝构造函数也是特殊的成员函数,其特征如下:
1. 拷贝构造函数是构造函数的一个重载形式。
2. 拷贝构造函数的 参数只有一个 且 必须是类类型对象的引用 ,使用 传值方式编译器直接报错 ,因为会引发无穷递归调用。
我们来思考一下,为什么不用引用会引发无穷递归?
如果我们采用值传递,那么传递的过程又是拷贝的过程,又得调用拷贝构造,这样不就无限套娃去了吗,编译器也不会同意这样做的,会直接报错。
class Time
{
public:
Time()
{
_hour = 1;
_minute = 1;
_second = 1;
}
Time(const Time& t)
{
_hour = t._hour;
_minute = t._minute;
_second = t._second;
cout << "Time::Time(const Time&)" << endl;
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
private:
// 基本类型(内置类型)
int _year = 1970;
int _month = 1;
int _day = 1;
// 自定义类型
Time _t;
};
int main()
{
Date d1;
// 用已经存在的d1拷贝构造d2,此处会调用Date类的拷贝构造函数
// 但Date类并没有显式定义拷贝构造函数,则编译器会给Date类生成一个默认的拷贝构
//造函数
Date d2(d1);
return 0;
}
这样就将d1浅拷贝给了d2,同时,拷贝构造函数中也可以这样写:
Time(const Time& t)
{
this->_hour = t._hour;
this-> _minute = t._minute;
this-> _second = t._second;
cout << "Time::Time(const Time&)" << endl;
}
这里面得this就是默认要拷贝对象的地址。
注意:在编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定义类型是调用其拷贝构造函数完成拷贝的。
class Stack
{
private:
int* _a;
int _top;
int _capacity;
public:
Stack(int capacity = 4)
{
_a = (int*)malloc(sizeof(int) * capacity);
if (!_a)
{
perror("malloc fail\n");
exit(-1);
}
_top = 0;
_capacity = capacity;
}
~Stack()
{
free(_a);
_a = nullptr;
_top = 0;
_capacity = 0;
}
};
int main()
{
Stack s1;
Stack s2(s1);
return 0;
}
当我们运行时:
程序直接崩了,为什么呢?
经过调试分析我们不难发现:
拷贝过的对象的属性一摸一样,就连_a也是一样的,而析构时又将同一块地址释放两次,当然得出问题了。这里拷贝必须用深拷贝(这个我们放到后面来讲)
- 使用已存在对象创建新对象
- 函数参数类型为类类型对象
- 函数返回值类型为类类型对象
class Date
{
public:
Date(int year, int minute, int day)
{
cout << "Date(int,int,int):" << this << endl;
}
Date(const Date& d)
{
cout << "Date(const Date& d):" << this << endl;
}
~Date()
{
cout << "~Date():" << this << endl;
}
private:
int _year;
int _month;
int _day;
};
Date Test(Date d)
{
Date temp(d);
return temp;
}
int main()
{
Date d1(2022,1,13);
Test(d1);
return 0;
}
但是我们用引用传参的话效率就要高一些。
我们再来看一个题:
class WidGet
{
public:
WidGet()
{
cout << "WidGet()" << endl;
}
WidGet(const WidGet&)
{
cout << "WidGet(const WidGet&)" << endl;
}
};
WidGet f(WidGet u)
{
WidGet v(u);
WidGet x = u;
return x;
}
int main()
{
WidGet s;
WidGet q = f(f(s));
return 0;
}
求上面一共调用了多少次拷贝构造函数?
我们分析一遍发现好像要调用构造拷贝9次,但是当我们运行程序时:
为啥程序只运行了7次呢?
我们的分析是没问题的,但是在这里编译器做了优化处理,将第4次和第5次优化成了一次,将第7次和第8次也优化成了一次。
5.赋值运算符重载
5.1 运算符重载
C++ 为了增强代码的可读性引入了运算符重载 , 运算符重载是具有特殊函数名的函数 ,也具有其 返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。函数名字为:关键字 operator 后面接需要重载的运算符符号 。函数原型: 返回值类型 operator 操作符 ( 参数列表 )
注意:
- 不能通过连接其他符号来创建新的操作符:比如operator@
- 重载操作符必须有一个类类型参数
- 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不能改变其含义
- 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
- .* :: sizeof ?: . 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
我们实现用一个运算符重载来实现判断两个类的大小:
class Date
{
public:
Date(int year=0,int month=1,int day=1)
{
_year = year;
_month = month;
_day = day;
}
//private:
int _year;
int _month;
int _day;
};
bool operator> (const Date& d1, const Date& d2)
{
if (d1._year > d2._year)
return true;
else if (d1._year == d2._year && d1._month > d2._month)
return true;
else if (d1._year == d2._year && d1._month == d2._month && d1._day > d2._day)
return true;
else
return false;
}
int main()
{
Date d1(2022,12,23);
Date d2(2022, 12, 24);
cout << operator>(d1, d2) << endl;
return 0;
}
不知道大家注意到了没有,在Date类实现的时候我将成员函数的限定符改为了public,不然在operator中就无法用类中的成员函数了,当然我们自己也可以在类里面实现一个GetYear(),
GetMonth( ),和Getday( ),不过这样也比较麻烦,这里其实可以用我们后面学习的友元解决,但是这样与我们这里实现的一样封装性就没有了保证,比较好的方式是重载成成员函数:
bool operator> (const Date& d)
{
if (_year > d._year)
return true;
else if (_year == d._year && _month > d._month)
return true;
else if (_year == d._year && _month == d._month && _day > d._day)
return true;
else
return false;
}
我们可能会有些疑问:为什么参数会变成了一个呀?其实这里会有一个隐藏的this指针,
(const Date& d) -> (Date* const this,const Date& d)
像我们下面这两种方式的调用都是没问题的:
cout <<(d1 > d2) << endl;
cout << d1.operator>(d2) << endl;
5.2 赋值运算符重载
1. 赋值运算符重载格式
- 参数类型:const T&,传递引用可以提高传参效率
- 返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值
- 检测是否自己给自己赋值
- 返回*this :要复合连续赋值的含义
有了前面的铺垫讲解这里就轻松许多了:
Date& operator=(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
return *this;
cout << "void operator=(const Date& d)" << endl;
}
我们可以调试起来看看:
可以很明显发现是赋值成功的,这里大家或许又会有疑问了,我怎么知道是调用赋值还是拷贝?
具体用法是有差别的,可以来看看:
Date d3(2022, 12, 24);
Date d4=d3;//赋值
//d4.operator=(d3);//赋值
Date d5(d3);//拷贝
那为什么返回值要用Date呢?
这样是为了实现链式调用,比如下面:
Date d3(2022, 12, 24);
Date d4, d5, d6, d7;
d4 = d5 = d6 = d7 = d3;
我们调试起来看:
这种链式赋值写起来方便很多。
2. 赋值运算符只能重载成类的成员函数不能重载成全局函数
Date& operator=(Date& left, const Date& right)
{
if (&left != &right)
{
left._year = right._year;
left._month = right._month;
left._day = right._day;
}
return left;
}
当我们编译时:
为什么呢?
原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。
在C++Prime中也有说明:
3. 用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。
注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值。
这个我们之前都有讲,这里就很容易理解了。像日期类是不需要我们自己实现的,但是Stack类的赋值就必须我们自己实现。
注意:如果类中未涉及到资源管理,赋值运算符是否实现都可以;一旦涉及到资源管理则必须要实现。
5.3 前置++和后置++重载
// 前置++:返回+1之后的结果
// 注意:this指向的对象函数结束后不会销毁,故以引用方式返回提高效率
Date& operator++()
{
_day += 1;
return *this;
}
// 后置++:
// 前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载
// C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递
// 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给
// this + 1
// 而temp是临时对象,因此只能以值的方式返回,不能返回引用
Date operator++(int)
{
Date temp(*this);
_day += 1;
return temp;
}
其中需要注意的地方我都给予了注释。
6 日期类的完善
Date.h:
#pragma once
#include<iostream>
using namespace std;
class Date
{
private:
int _year;
int _month;
int _day;
public:
/*Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
cout << "Date(const Date& d)" << endl;
}*/
int GetMonthDay(int year, int month);
Date(int year = 1, int month = 1, int day = 1);
void Print();
//日期+=天数
Date& operator+=(int day);
//日期-=天数
Date& operator-=(int day);
//日期+天数
Date operator+(int day)const;
//日期-天数
Date operator-(int day)const;
//前置++
Date& operator++();
//后置++
Date operator++(int)const;
//前置--
Date& operator--();
//后置--
Date operator--(int)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;
//日期-日期,返回天数
int operator-(const Date& d)const;
//返回指定日期是周几
void PrintWeek()const;
};
Date.cpp:
#define _CRT_SECURE_NO_WARNINGS 1
#include"Date.h"
int Date::GetMonthDay(int year, int month)
{
static int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int day = days[month];
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
day += 1;
return day;
}
Date::Date(int year , int month , int day )//声明给了缺省值,定义就不需要给了
{
if (year >= 1 && month >= 1 && month <= 12 && day >= 1 && day <= GetMonthDay(year, month))
{
_year = year;
_month = month;
_day = day;
}
else
{
cout << "输入非法" << endl;
cout << year << "-" << month << "-" << day << endl;
}
}
void Date::Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
//日期+=天数
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)
{
_month = 1;
_year++;
}
}
return *this;
}
//日期-=天数
Date& Date::operator-=(int day)
{
if (day < 0)
{
//return operator+=(abs(day));
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 = Date(*this);
//tmp.operator+=(day);
tmp += day;
return tmp;
}
//日期-天数
Date Date::operator-(int day)const
{
Date tmp = Date(*this);
tmp -= day;
return tmp;
}
//前置++
Date& Date::operator++()
{
return *this += 1;
}
//后置++
Date Date::operator++(int)const
{
Date tmp(*this);
tmp += 1;
return tmp;
}
//前置--
Date& Date::operator--()
{
return *this -= 1;
}
//后置--
Date Date::operator--(int)const
{
Date tmp(*this);
tmp -= 1;
return tmp;
}
//>运算符重载
bool Date::operator>(const Date& d)const
{
if (_year > d._year)
return true;
else if (_year == d._year && _month > d._month)
return true;
else if (_year == d._year && _month == d._month && _day > d._day)
return true;
else
return false;
}
//==运算符重载
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) || (*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 !(*this == d);
}
//日期-日期,返回天数
int Date::operator-(const Date& d)const
{
int flag = 1;
Date big = *this;
Date small = d;
int count = 0;
if (small>big)
{
flag = -1;
big=(d);
small=*this;
}
while (big != small)
{
++small;
//small++;不要用small++
count++;
}
return count * flag;
}
//返回指定日期是周几
void Date::PrintWeek()const
{
const char* str[7] = { "星期一","星期二", "星期三", "星期四", "星期五", "星期六", "星期天" };
//假定以1910年1月3号位基准
//这里并没有实例化出对象,所以要把初始值给好
int day = *this - Date (2000,1,3);
cout << str[day % 7] << endl;
}
7.const成员
将 const 修饰的 “ 成员函数 ” 称之为 const 成员函数 , const 修饰类成员函数,实际修饰该成员函数隐含的 this 指针 ,表明在该成员函数中 不能对类的任何成员进行修改。
1. const 对象可以调用非 const 成员函数吗?2. 非 const 对象可以调用 const 成员函数吗?3. const 成员函数内可以调用其它的非 const 成员函数吗?4. 非 const 成员函数内可以调用其它的 const 成员函数吗?
class A
{
public:
void Print()
{
cout << "Print( )" << endl;
}
private:
int _a;
int _b;
};
int main()
{
const A aa;
aa.Print();
return 0;
}
这种const对象可以调用非const成员函数是会直接报错的:
而非const调用const是不会的:
class A
{
public:
void Print()const
{
cout << "Print( )const" << endl;
}
private:
int _a;
int _b;
};
int main()
{
A aa;
aa.Print();
return 0;
}
这也是我们之前提到过权限放大缩小的问题,允许权限缩小,不允许权限放大。
后面两个问题我就不再实现了,大家有兴趣下来自己可以实现来看看,这里我给出结论:
8.取地址及const取地址操作符重载
这两个默认成员函数一般不用重新定义 ,编译器默认会生成。
class Date
{
public :
Date* operator&()
{
return this ;
}
const Date* operator&()const
{
return this ;
}
private :
int _year ; // 年
int _month ; // 月
int _day ; // 日
};
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如 想让别人获取到指定的内容!
9 总结
本篇博客向大家介绍了类的6个默认函数,重点向大家介绍了构造函数,析构函数,拷贝构造函数,赋值运算符重载,还实现了一个比较完整的日期类来巩固对这几个函数的理解和加深,类和对象最重要的一节就到此结束了,还有一些零碎的关于类和对象的知识将放在下一篇博客来讲,我们下期再见啦!