目录
1、类的6个默认成员函数
大家在用C语言写结构的时候,会不会老是忘了初始化,或者忘了清理空间。祖师爷在设计C++前估计也是这样,所以在类里面加了默认成员函数来辅助。
什么是默认成员函数呢?
任何类在什么都不写时,编译器会自动生成的成员函数叫默认成员函数。分别是以下6个:
2、构造函数
构造函数是一个特殊的成员函数,创建类类型对象时由编译器自动调用,主要任务是初始化对象,并且在对象的整个生命周期内只调用一次。
2.1、特性
- 函数名与类名相同。
- 无返回值(也不需要写void)。
- 对象实例化时编译器自动调用对应的构造函数。
- 构造函数可以重载(比如无参的和带参的)。
- 若用户未显式定义,编译器生成默认无参构造函数;若用户显式定义,则编译器不再生成。
拿日期类举例:
class Date
{
public:
// 1.无参构造函数
Date()
{}
// 2.带参构造函数
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
注意:调用无参构造函数时,对象后不加括号,避免与函数声明混淆。
Date d1; // 正确:调用无参构造函数
Date d2(); // 错误:声明函数d2,返回Date类型
Date d3(2023,3,3); //调用带参的构造函数
默认生成的构造:
注意:当我们不写构造函数的时候,编译器默认生成的构造函数对内置类型不做处理(有些编译器也会处理),初始化的值依然是随机值,自定义类型会去调用他的默认构造。
- 内置类型/基本类型:语言本身定义的基础类型,如int/char/double/指针等等
- 自定义类型:用struct/class等等定义的类型
所以,一般情况下,有内置类型成员,就需要自己写构造函数,不能用编译器自己生成的。全部都是自定义类型成员可以考虑让编译器自己生成。
在C++11又打了补丁:允许为内置类型成员变量声明默认值。
class Date
{
private:
//C++11支持,这里不是初始化,因为这里只是声明
//这里给的是默认的缺省值,给编译器生成默认构造函数用
int _year = 1970;
int _month = 1;
int _day = 1;
};
3、析构函数
析构函数:与构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由 编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作。
3.1、特性
-
函数名为~类名,无参数和返回值。
-
对象生命周期结束时自动调用,用于释放资源(如堆内存)。
-
不可重载,每个类只有一个析构函数。
-
若未显式定义,编译器生成默认析构函数(对自定义类型成员调用其析构函数)。
比如:
class stack
{
public:
//析构函数
~Stack()
{
if (_array)
{
free(_array); // 释放堆内存
_array = nullptr;
}
}
private:
int* _array;
int _capacity;
int _size;
};
系统自动生成默认的析构函数,对内置类型不做处理,自定义类型会去调用它的析构函数。
- 一般情况下,有动态申请的资源,就需要显示写析构函数释放资源
- 没有动态申请的资源,不需要写析构
- 需要释放资源的成员都是自定义类型,不需要写析构
4、拷贝构造函数
拷贝构造函数:用一个对象拷贝出另一个对象,只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用。
4.1、特性
1、函数名:类名(const 类名& 对象)。是构造函数的一种重载形式。
2、拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错, 因为会引发无穷递归调用。
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// Date(const Date& d) // 正确写法
Date(Date d) // 错误写法:编译报错,会引发无穷递归
{
_year = d._year;
_month = d._month;
_day = d._day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
Date d2(d1);//拷贝构造调用
return 0;
}
传值调用而无穷递归的原因是:C++规定,传值调用内置类型直接拷贝,自定义类型必须调用拷贝构造完成拷贝,所以传值调用前会先进行拷贝构造,拷贝构造完又会形成新的拷贝构造,会这样无穷递归下去。
3、若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。
默认生成的拷贝构造:
- 内置类型成员完成值拷贝/浅拷贝。
- 自定义类型成员会调用它的拷贝构造
注:类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请时,则拷贝构造函数是一定要写的,否则就是浅拷贝。
比如:
typedef int DataType;
class Stack
{
public:
Stack(size_t capacity = 10)
{
_array = (DataType*)malloc(capacity * sizeof(DataType));
if (nullptr == _array)
{
perror("malloc申请空间失败");
return;
}
_size = 0;
_capacity = capacity;
}
void Push(const DataType& data)
{
// CheckCapacity();
_array[_size] = data;
_size++;
}
~Stack()
{
if (_array)
{
free(_array);
_array = nullptr;
_capacity = 0;
_size = 0;
}
}
private:
DataType *_array;
size_t _size;
size_t _capacity;
};
int main()
{
Stack s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
Stack s2(s1);//调用拷贝构造
return 0;
}
上面代码,构造中申请了资源,Stack s2(s1);这里调用拷贝构造用的是系统默认的拷贝构造,也就是完成浅拷贝,将s1的内容一点不差的全拷到s2,这会导致s1和s2所指向的地址相同,那么在析构的时候,就会在同一个位置析构两次,一块内存多次释放,会造成程序崩溃。
5、运算符重载
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其 返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。就是让自定义类型的数据也可以有=,+、-、<、>等操作符的特性。
5.1、规则
函数名字为:关键字operator后面接需要重载的运算符符号。
函数原型:返回值类型 operator操作符(参数列表)
注意:
- 不能通过连接其他符号来创建新的操作符:比如operator@
- 重载操作符必须有一个类类型参数用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义
- 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐 藏的this
- .* :: sizeof ?: . 注意以上5个运算符不能重载。
5.2、赋值运算符重载(默认成员函数)
1. 赋值运算符重载格式(... operator=(...))
- 参数类型:const T&,传递引用可以提高传参效率
- 返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值 检测是否自己给自己赋值
- 返回*this :要复合连续赋值的含义
比如实现一个日期类的赋值运算符重载:
class Date
{
public :
Date(int year = 1900, 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 ;
};
int main()
{
Date d1;
Date d2;
d2 = d1;//赋值运算
return 0;
}
2. 用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。
默认生成的赋值重载跟拷贝构造行为一样:
- 内置类型成员--值拷贝/浅拷贝
- 自定义类型成员会去调用它的赋值重载
注意:如果类中未涉及到资源管理,赋值运算符是否实现都可以;一旦涉及到资源管理则必须要实现。原因跟拷贝构造的一样。
5.3、其余运算符重载
实现一个日期类:
#include<assert.h>
#include<iostream>
using namespace std;
class Date
{
//友元函数声明
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);
public :
Date(int year = 1, int month = 1, int day = 1);
void Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
void operator=(const Date& d);
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;
static int GetMonthDay(int year, int month);
Date& operator+=(int day);
Date operator+(int day) const;
//前置++
Date& operator++();
//后置++
Date operator++(int);
Date& operator-=(int day);
Date operator-(int day) const;
//前置--
Date& operator--();
//后置--
Date operator--(int);
//日期-日期
int operator-(const Date& d) const;
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& out,const Date& d);
istream& operator>>(istream& in, Date& d);
#include"date.h"
Date::Date(int year, int month, int day)
{
if (month > 0 && month < 13 && day <= GetMonthDay(year, month) && day > 0)
{
_year = year;
_month = month;
_day = day;
}
else
{
cout << "非法日期" << endl;
assert(false);
}
}
void Date::operator=(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
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;
}
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::GetMonthDay(int year, int month)
{
int arr[13] = { 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;
}
else
{
return arr[month];
}
}
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 += day;
while (tmp._day > GetMonthDay(tmp._year, tmp._month))
{
tmp._day -= GetMonthDay(tmp._year, tmp._month);
tmp._month++;
if (tmp._month == 13)
{
tmp._year++;
tmp._month = 1;
}
}*/
tmp += day;
return tmp;
}
Date& Date::operator++()
{
*this += 1;
return *this;
}
Date Date::operator++(int)
{
Date tmp = *this;
*this += 1;
return tmp;
}
Date& Date::operator-=(int day)
{
if (day < 0)
{
return *this += -day;
}
_day -= day;
while (_day <= 0)
{
--_month;
if (_month == 0)
{
_year--;
_month = 12;
}
_day += GetMonthDay(_year, _month);
}
return *this;
}
Date Date::operator-(int day) const
{
Date tmp = *this;
tmp -= day;
return tmp;
}
Date& Date::operator--()
{
*this -= 1;
return *this;
}
Date Date::operator--(int)
{
Date tmp = *this;
*this -= 1;
return tmp;
}
//d1-d2
int Date::operator-(const Date& d) const
{
Date max = *this;
Date min = d;
int flag = 1;//默认大的减小的
if (max < min)
{
max = d;
min = *this;
flag = -1;
}
int count = 0;//相差天数
while (min != max)
{
min++;
count++;
}
return count*flag;
}
ostream& operator<<(ostream& out,const Date& d)
{
out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
return out;
}
istream& operator>>(istream& in, Date& d)
{
int year, month, day;
in >> year >> month >> day;
if (month > 0 && month < 13 && day>0 && day <= Date::GetMonthDay(year, month))
{
d._year = year;
d._month = month;
d._day = day;
}
else
{
cout << "非法日期" << endl;
assert(false);
}
return in;
}
6、取地址及const取地址操作符重载
将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。
这两个默认成员函数一般不用重新定义 ,编译器默认会生成
Date* operator&()
{
return this; // 普通对象取地址
}
const Date* operator&() const //成员函数后面加const以后,普通和const成员对象都可以调用
{
return this; // const对象取地址
}