目录
1.类有六个默认成员函数
如果一个类中没有成员,则称为空类。
但是空类中真的什么都没有吗?并不是,任何类在什么都不写时,编译器会自动生成以下6个默认成员函数。
默认成员函数:用户没有显式实现,但编译器会自动生成的成员函数称为默认成员函数。
class Date{};
2.构造函数
2.1 概念
对于Date类
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(2024, 3, 2);
d1.Print();
Date d2;
d2.Init(2024, 2, 23);
d2.Print();
return 0;
}
上述Date类,我们可以通过 Init 公有方法给对象设置日期,但如果每次创建对象时都调用该方法设置信息,过于麻烦,是否可以在对象创建时,就将信息设置进去?
构造函数 是 一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,以保证每个数据成员都有一个合适的初始值,并且在对象整个生命周期内只调用一次。
2.2 特性
构造函数是特殊的成员函数,虽然构造函数的名称叫构造,但是构造函数的主要任务并不是开空间创建对象,而是初始化对象。
特征如下:
- 函数名与类名相同。
- 没有返回值。
- 对象实例化时编译器自动调用对应的构造函数。
- 构造函数可以重载。
class Date
{
public:
//1.无参构造函数
Date(){}
//2.有参构造函数
Date(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;//日
};
void Test()
{
//调用无参的构造函数
Date d1;
//调用有参的构造函数
Date d2(2024, 3, 2);
d1.Print();
d2.Print();
//注意:如果通过无参构造函数创建对象时,对象后面不用跟括号,否则就变成 函数声明
//下面代码的函数,声明了d3函数,该函数无参,返回一个日期类型的的对象。
//C4930 “Date d3(void)”: 未调用原型函数(是否是有意用变量定义的?)
Date d3();//err
}
5.如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义,则编译器将不再生成。
class Date
{
public:
//用户显式定义构造函数,编译器则不再生成
/*Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}*/
private:
int _year;//年
int _month;//月
int _day;//日
};
int main()
{
//无参构造函数,放开后报错:error C2512: “Date”: 没有合适的默认构造函数可用
Date d1;
return 0;
}
将Date类 中构造函数注释后,代码可以通过编译,因为编译器生成了一个无参的默认构造函数。
将Date类 中构造函数解除注释,代码则编译失败,因为一旦显式定义任何构造函数,编译器将不再生成。
再显式定义有参构造函数后,又去调用无参构造函数,代码会编译失败。
6.默认构造函数的用法: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;
}
运行结果:
Time()
注意:C++11 中针对内置类型成员不初始化的缺陷,又打了补丁,即:内置类型成员变量中声明时可以给默认值。
7.无参的构造函数和全缺省的构造函数都成为默认构造函数,并且默认构造函数只能有一个。注意:无参构造函数、全缺省构造函数,我们没写编译器默认生成的构造函数,都可以认为时默认构造函数。
class Date
{
public:
Date()
{
_year = 1970;
_month = 1;
_day = 1;
}
Date(int year = 1970, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
private:
//内置类型(基本类型)
int _year;
int _month;
int _day;
};
void Test()
{
Date d1;//err,对重载函数的调用不明确
}
一般无参构造函数和全缺省构造函数只能出现一次,否则会出现调用不明确的问题。也就是默认构造函数只能有一个。
3.析构函数
概念
析构函数:与构造函数的功能相反,析构函数不是完成对象本身的销毁,局部对象销毁工作是由编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作。
特性
析构函数是特殊的成员函数,特征如下:
- 析构函数名是在类名前加上字符 ~。
- 无参数无返回值类型。
- 一个类只能由一个析构函数,若未显式定义,系统会自动生成默认的析构函数。注意:析构函数不能重载。
- 对象生命周期结束时,C++编译系统自动调用析构函数。
typedef int DataType;
class Stack
{
public:
//构造函数:初始化
Stack(size_t capacity = 4)
{
_arr = (DataType*)malloc(sizeof(DataType) * capacity);
if (NULL == _arr)
{
perror("malloc申请空间失败!");
exit(1);
}
_capacity = capacity;
_top = 0;
}
void Push(DataType data)
{
//CheckCapacity();
_arr[_top] = data;
_top++;
}
//其他一些方法.....
//析构函数 -- 清理资源
~Stack()
{
if (_arr)
{
free(_arr);
_arr = nullptr;
_top = _capacity = 0;
}
}
private:
DataType* _arr;
int _top;
int _capacity;
};
void TestStack()
{
Stack st;
st.Push(1);
st.Push(2);
}
5.编译器生成的默认析构函数,对自定义类型成员调用它的析构函数。
class Time
{
public:
~Time()
{
cout << "~Time()" << endl;
}
private:
//基本类型(内置类型)
int _hour;
int _minute;
int _second;
};
class Date
{
private:
//内置类型(基本类型)
int _year;
int _month;
int _day;
//自定义类型
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对象销毁时,要保证其内部每个自定义对象都可以正确销毁(释放),main函数中并没有直接调用Time 类析构函数,而是显式调用编译器为Date类生成的默认析构函数。
注意:创建哪个类的对象则会调用该类的析构函数,销毁哪个类的对象则调用该类的析构函数。
6.如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,比如:Date类;有申请资源时,一定要写,否则会出现资源泄露,比如:Stack类、Queue类....
4.拷贝构造函数
在创建对象时,是否可以创建一个与已存在对象一样的新对象呢?
拷贝构造函数:只有一个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时有编译器自动调用。
特征
拷贝构造函数也是特殊的成员函数,其特征如下:
- 拷贝构造函数是构造函数的一个重载形式。
- 拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错,因为会引发无穷的递归调用。
class Date
{
public:
Date(int year = 1970, 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;
}
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
//内置类型(基本类型)
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024,1,2);
d1.Print();
Date d2(d1);
d2.Print();
return 0;
}
运行结果:
2024/1/2
2024/1/2
3.如果没有显式定义,编译器会生成默认 拷贝构造函数。默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者叫做值拷贝。
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(const Time& t)" << 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;
Date d2(d1);
return 0;
}
分析:用已经存在的 d1 拷贝构造 d2 ,此处会调用Date类的拷贝构造函数,但是Date类并没有显式定义拷贝构造函数,则编译器会给Date类生成一个默认的拷贝构造函数。
注意:在编译器生成的默认拷贝构造函数中
内置类型是按照字节方式直接拷贝的;
自定义类型是调用其拷贝构造函数完成拷贝的。
4.编译器生成迭代默认拷贝构造函数已经可以完成字节序的值拷贝,是否还需要自己显式实现?
当然像日期类这样的类是没有必要的。那么看看下面的类呢?
typedef int DataType;
class Stack
{
public:
//构造函数:初始化
Stack(size_t capacity = 10)
{
_arr = (DataType*)malloc(sizeof(DataType) * capacity);
if (NULL == _arr)
{
perror("malloc申请空间失败!");
exit(1);
}
_capacity = capacity;
_top = 0;
}
void Push(DataType data)
{
//CheckCapacity();
_arr[_top] = data;
_top++;
}
//其他一些方法.....
//析构函数 -- 清理资源
~Stack()
{
if (_arr)
{
free(_arr);
_arr = nullptr;
_top = _capacity = 0;
}
}
private:
DataType* _arr;
int _top;
int _capacity;
};
int main()
{
Stack st1;
st1.Push(1);
st1.Push(2);
st1.Push(3);
Stack st2(st1);
return 0;
}
可以看到这段程序会崩溃掉,需要我们使用深拷贝去解决。
注意:
类中如果没有涉及资源申请时,拷贝构造函数可写可不写;
一旦涉及到资源申请时,则拷贝函数一定要写,否则就是浅拷贝。
5.拷贝构造函数典型调用场景:
- 使用已存在对象创建新对象
- 函数参数类型为类类型对象
- 函数返回值类型为类类型对象
当然,为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用尽量使用引用。
5.赋值运算符
5.1运算符重载
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名称以及参数列表器返回值类型普通函数类似。
函数名称:关键字operator后面接需要重载的运算符号。
函数原型:返回值类型 operator操作符(参数列表)。
注意:
- 不能通过其它符号来创建新的操作符:如operator@ ;
- 重载操作符必须有一个类类型对象;
- 哟与内置类型的运算符,其含义不能改变,例如:内置的整数+,不饿能改变其含义;
- 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的 this;
- ".*" , " :: " , "sizeof " , " ? :" , " . ",注意以上5个运算符不能重载。
定义全局的operator ==
class Date
{
public:
Date(int year, int month, int day)
{
_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;
}
void TestDate()
{
Date d1(2024, 3, 1);
Date d2(2024, 1, 2);
cout << (d1 == d2) << endl;
}
会发现运算重载成全局的,成员变量需要定义为公有的,那么就没有封装性了。这里其实可以使用友元解决,或者重载成成员函数。
这里把operator==重载成成员函数。
class Date
{
public:
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
//bool operator == (Date* this,const Date& d)
//注意:左操作数是 this, 指向调用函数的对象
bool operator == (const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
private:
int _year;
int _month;
int _day;
};
void TestDate()
{
Date d1(2024, 3, 1);
Date d2(2024, 1, 2);
cout << (d1 == d2) << endl;
}
5.2 赋值运算符重载
1.赋值运算的重载格式
- 参数类型:const T&,传递引用可以提高传参效率;
- 返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值;
- 检测是否自己给自己赋值;
- 返回*this:要符合连续赋值的含义。
class Date
{
public:
Date(int year = 1970, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
Date operator = (const Date& d)
{
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
bool operator == (const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
private:
int _year;
int _month;
int _day;
};
2.赋值运算符只能重载成类成员函数不能重载成全局函数
class Date
{
public:
Date(int year = 1970, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
int _year;
int _month;
int _day;
};
Date& operator=(const Date& d1, const Date& d2)
{
if (&d1 != &d2)
{
d1._year = d2._year;
d1._month = d2._month;
d1._day = d2._day;
}
return d1;
}
编译失败:error C2801: "operator = "必须是非静态成员
原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户又在类外自己实现一个全局的赋值运算符重载,就会和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。
我们可以重载赋值运算符。不论形参的类型是什么,赋值运算符都必须定义为成员函数。
3.用户没有显式实现时,编译器会生成一个摩恩赋值运算符重载,以值的方式逐字节拷贝。
注意:内置类型成员变量是直接赋值的
自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值。
class Time
{
public:
Time()
{
_hour = 12;
_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;
int _month;
int _day;
//自定义类型
Time _t;
};
int main()
{
Date d1;
Date d2;
d1 = d2;
return 0;
}
对于日期类,编译器生成的默认赋值运算符重载函数已经可以完成字节序的值拷贝,不需要自己实现赋值运算符重载,那么其他类呢?
比如:栈(Stack)
typedef int DataType;
class Stack
{
public:
//构造函数:初始化
Stack(size_t capacity = 4)
{
_arr = (DataType*)malloc(sizeof(DataType) * capacity);
if (NULL == _arr)
{
perror("malloc申请空间失败!");
exit(1);
}
_capacity = capacity;
_top = 0;
}
void Push(DataType data)
{
//CheckCapacity();
_arr[_top] = data;
_top++;
}
//其他一些方法.....
//析构函数 -- 清理资源
~Stack()
{
if (_arr)
{
free(_arr);
_arr = nullptr;
_top = _capacity = 0;
}
}
private:
DataType* _arr;
int _top;
int _capacity;
};
int main()
{
Stack st1;
st1.Push(1);
st1.Push(2);
st1.Push(3);
Stack st2;
st1 = st2;
return 0;
}
答案是要自己实现赋值运算符重载,否则上述代码会崩溃,需要我们使用深拷贝实现。
我们只要知道:如果类中没有涉及到资源管理,赋值运算符是否实现都可以;一旦涉及到资源管理必须要实现。
5.3 前置++ 和 后置++ 重载
前置++ 和 后置++ 都是一元运算符,为了让前置++和后置++形成正确重载
C++规定:
operator++() -- 表示前置++
operator++(int) -- 表示后置++,虽然后置++重载时增多了一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递。
class Date
{
public:
Date(int year = 1970, 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
//tmp是临时对象,因此只能以值的方式返回,不能返回引用
Date operator++(int)
{
Date tmp(*this);
_day += 1;
return tmp;
}
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 3, 1);
Date ret1 = d1++;
ret1.Print();
d1.Print();
Date ret2 = ++d1;
ret2.Print();
d1.Print();
return 0;
}
运行结果:
2024/3/1
2024/3/2
2024/3/3
2024/3/3
6.日期类
#include <iostream>
using namespace std;
//日期类的实现
class Date
{
public:
//获取每月有多少天
int GetMonthDay(int year, int month)
{
int MonthArray[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;
}
return MonthArray[month];
}
Date(int year, int month, int day) {
_year = year;
_month = month;
_day = day;
//检查日期是否合法
if (month < 1 || month > 12
|| day < 1 || day > GetMonthDay(year, month))
{
cout << "非法日期" << endl;
//exit(1);
}
}
//void Print(const Date* this)
void Print() const
{
cout << _year << "年" << _month << "月" << _day << "日" << endl;
}
Date& operator = (const Date& d)//类型后面&是引用
{
if (this != &d)//&d 取地址
{
this->_year = d._year;
this->_month = d._month;
this->_day = d._day;
}
return *this;
}
// < 运算符重载
//d1 < d2
//d1.operator < (d2)
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;
}
}
// == 运算符重载
//d1 == d2
bool operator == (const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
// <= 运算符重载
bool operator <= (const Date& d)
{
return *this < d || *this == d;
}
// > 运算符重载
bool operator>(const Date& d)//第一个操作数是隐藏的this
{
return !(*this <= d);
}
// != 运算符重载
bool operator != (const Date& d)
{
return !(*this == d);
}
// >= 运算符重载
bool operator >= (const Date& d)
{
return !(*this < d);
}
//2023 7 23
//0 次拷贝
//日期 += 天数
Date& operator += (int day)
{
if (day < 0)
{
return *this -= (-day);
}
_day += day;//先把传过来的天数给给_day
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
++_month;
if (_month == 13)
{
++_year;
_month = 1;
}
}
return *this;
}
//d1 + 100
//两次拷贝
//日期 + 天数
Date operator+(int day)
{
Date tmp(*this);
tmp += day;
return tmp;
}
//日期 -= 天数
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 operator-(int day)
{
Date tmp(*this);
tmp -= day;
return tmp;
}
//++d1
//前置++
Date& operator++()
{
*this += 1;
return *this;
}
//d1++
//后置++
Date operator++(int)
{
Date tmp(*this);
*this += 1;
return tmp;
}
//前置--
Date operator--()
{
*this -= 1;
return *this;
}
//后置--
Date operator--(int)
{
Date tmp(*this);
*this -= 1;
return tmp;
}
//日期 - 日期 = 天数
int operator-(const Date& d)
{
//默认左大右小
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;
}
private:
int _year;
int _month;
int _day;
};
7.const修饰成员
将const 修饰的 ”成员函数“ 称为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。
#include <iostream>
using namespace std;
class Date
{
public:
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
void Print() const
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year; //年
int _month; //月
int _day; //日
};
void Test()
{
Date d1(2024,3,25);
d1.Print();
const Date d2(2024,3,25);
d2.Print();
}
可以看到实例化的类对象被const修饰后,不能调用该类中的成员函数。解决方案是在该成员函数后加上const。如下图写法:
8.取地址与const取地址操作符重载
这两个默认成员函数一般不用重新定义,编译器默认会生成。
class Date
{
public:
Date* operator&()
{
return this;
}
const Date* operator&() const
{
return this;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
上述两个运算符一般不用重载,使用编译器默认生成的默认取地址的重载即可,在特殊情况下,才需要重载,例如:想让别人获取到指定的内容。