在C语言结构体中,创建变量需要调用初始化函数来变量设置一些信息。但实际项目中,如果每个变量都通过这种方式来设置相关信息,未免过于繁琐。为此,C++为我们提供了构造函数。
构造函数是一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,以保证每个数据成员都有 一个合适的初始值,并且在对象整个生命周期内只调用一次。
需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象,而是初始化对象。
其特征如下:
Tips:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数都称为默认构造函数,并且默认构造函数只能有一个。
分析:变量d实例化时,会调用对应的构造函数。但Date中没用显示的写,所以编译器会生成一个无参的默认构造函数。对于内置类型_year、_month、_day均初始化为1(由于我们在类中声明时给了初始值),而自定义类型_t调用其对应的默认构造函数。
#include
using namespace std;
class Time
{
public:
Time(int hour=1,int minute=1,int second=1)
{
cout << "Time()" << endl;
_hour = hour;
_minute = minute;
_second = second;
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
public:
void Print()
{
cout << _year << _month << _day << endl;
}
private:
// 基本类型(内置类型)
int _year=1;
int _month=1;
int _day=1;
// 自定义类型
Time _t;//调用对应的默认构造函数
};
int main()
{
Date d;//Date没有显示定义构造函数,编译器默认生成一个无参默认构造函数
return 0;
}
与构造函数功能相反,析构函数不是完成对对象本身的销毁(局部对象销毁工作是由编译器完成的),而是完成对象中资源的清理工作。(对象在销毁时会自动调用析构函数)
析构函数是特殊的成员函数,其特征如下:
class Time
{
public:
~Time()
{
cout << "~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 d;
return 0;
}
结果:程序运行结束后输出:~Time()
问:在main方法中根本没有直接创建Time类的对象,为什么最后会调用Time类的析构函数?(创建哪个类的对象则调用该类的析构函数,销毁那个类的对象则调用该类的析构函数)
解析:main方法中创建了Date对象d,而d中包含4个成员变量,其中_year, _month,_day三个是自定义类型,销毁时不需要资源清理,最后系统直接将其内存回收即可。而_t是Time类对对象,在对d销毁时,要将其内部包含的Time类的_t对象销毁,所以要调用Time类的析构函数。但是:main函数中不能直接调用Time类的析构函数,实际要释放的是Date类对象,所以编译器会调用Date类的析构函数,而Date没有显式提供,则编译器会给Date类生成一个默认的析构函数,目的是在其内部调用Time类的析构函数,即当Date对象销毁时,要保证其内部每个自定义对象都可以正确销毁。
拷贝构造函数:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用。
拷贝构造函数也是特殊的成员函数,其特征如下:
Tips:性质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(const 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;
}
解析:使用传值方式,我们发现调用拷贝构造函数时,需要先传参。而传参需要拷贝参数,又形成了一个新的拷贝构造函数。新的拷贝构造函数又需要传参拷贝参数,形成新的拷贝构造函数。不断循环下去,从而引发无穷递归。
问题1:编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式实现吗?(我们以栈为例,看看会发生什么?)
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();//由于栈创建时开了10个空间,博主保证足够用就在此不检查是否扩容问题了
_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;
}
解析:s2拷贝s1时,调用默认构造函数,发生值拷贝。导致s1和s2中的成员函数_array指向同一处地址。当程序结束时,s1、s2都会调用对应的析构函数,会导致同一块地址析构两次的问题。
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号。
函数原型:返回值类型 operator操作符(参数列表)
Tips:
实例:(以==为例,给出内置和全局两个版本)
【全局】:
// 全局的operator==
class Date
{
public:
Date(int year = 1900, 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)
{
return d1._year == d2._year
&& d1._month == d2._month
&& d1._day == d2._day;
}
int main()
{
Date d1(2023, 10, 4);
Date d2(2018, 9, 3);
cout << (d1 == d2) << endl;
return 0;
}
【内置】:
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// bool operator==(Date* this, const Date& d2),隐藏this指针
// 这里需要注意的是,左操作数是this,指向调用函数的对象
bool operator==(const Date& d2)
{
return _year == d2._year && _month == d2._month && _day == d2._day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2023, 10, 4);
Date d2(2023, 10, 3);
cout << (d1 == d2) << endl;
return 0;
}
。参数类型: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;
};
【实例】:
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
int _year;
int _month;
int _day;
};
// 赋值运算符重载成全局函数,注意重载成全局函数时没有this指针了,需要给两个参数
Date& operator=(Date& left, const Date& right)
{
if (&left != &right)
{
left._year = right._year;
left._month = right._month;
left._day = right._day;
}
return left;
}
分析:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。
注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值。
【实例】:
class Time
{
public:
Time()
{
_hour = 1;
_minute = 1;
_second = 1;
}
Time& operator=(const Time& t)
{
if (this != &t)
{
_hour = t._hour;
_minute = t._minute;
_second = t._second;
}
return *this;
}
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;
Date d2;
d1 = d2;
return 0;
}
既然编译器生成的默认赋值运算符重载函数已经可以完成字节序的值拷贝了,还需要自己实现吗?当然像上诉日期类这样的类是没必要的。那么下面的类呢?验证一下试试?
//这里会发现下面的程序会崩溃掉?这里就需要我们以后讲的深拷贝去解决。
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;
s2 = s1;
return 0;
}
前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载,C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递。
【实例】:
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// 前置++:返回+1之后的结果
// 注意:this指向的对象函数结束后不会销毁,故以引用方式返回提高效率
Date& operator++()
{
_day += 1;
return *this;
}
// 后置++:
// 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给this + 1
// 而temp是临时对象,因此只能以值的方式返回,不能返回引用
Date operator++(int)
{
Date temp(*this);
_day += 1;
return temp;
}
private:
int _year;
int _month;
int _day;
};