目录
1. 类的6个默认成员函数
如果一个类中什么成员都没有,简称为空类
空类中真的什么都没有吗?并不是,任何类在什么都不写时,编译器会自动生成以下6个默认成员
函数。
默认成员函数:用户没有显式实现,编译器会生成的成员函数称为默认成员函数
2. 构造函数
2.1 概念
对于以下Date类:
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
std::cout << _year << "-" << _month << "-" << _day << std::endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
d1.Init(2022, 7, 5);
d1.Print();
Date d2;
d2.Init(2022, 7, 6);
d2.Print();
return 0;
}
对于Date类,可以通过 Init 公有方法给对象设置日期,但如果每次创建对象时都调用该方法设置信息,未免有点麻烦,那能否在对象创建时,就将信息设置进去呢?
构造函数是一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,以保证每个数据成员都有 一个合适的初始值,并且在对象整个生命周期内只调用一次。
构造函数,之所以叫构造,那是因为要对对象里面的每个数据成员进行初始化,进行构造。它的目的,就是初始化!
4.2 特性
构造函数是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象,而是初始化对象!
其特征如下:
1. 函数名与类名相同。
2. 无返回值。
3. 对象实例化时编译器自动调用对应的构造函数。
4. 构造函数可以重载。
class Date
{
public:
//初始化
//1.无参构造函数
Date()
{
_year = 1;
_month = 1;
_day = 1;
}
//带参构造函数
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
void TestDate()
{
Date d1;//调用无参构造函数
Date d2(2022, 2, 2);//调用带参构造函数
}
看调试,在创建对象的同时,对象的初始化也完成了。
看特性的第四点,可以构成重载函数,同时使用缺省参数。
class Date
{
public:
//初始化
//1.无参构造函数
Date()
{
_year = 1;
_month = 1;
_day = 1;
}
//带参构造函数
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
可以知道,确实是重载函数,但是,却不能使用,因为有二义性。
另外需要注意的是,在无参的构造函数中,函数调用不能带(),否则就成了函数声明。
// 无参的不要像下面这样写
Date d4();
Date func();
重点:
5.如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。
注意这里的结果是:随机值!
class Date
{
public:
/*
// 如果用户显式定义了构造函数,编译器将不再生成
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;
};
int main()
{
// 将Date类中构造函数屏蔽后,代码可以通过编译,因为编译器生成了一个无参的默认构造函
数
// 将Date类中构造函数放开,代码编译失败,因为一旦显式定义任何构造函数,编译器将不再
生成
// 无参构造函数,放开后报错:error C2512: “Date”: 没有合适的默认构造函数可用
Date d1;
return 0;
}
看到这里,一定会疑问,虽然编译器会自己生成一个构造函数,但是生成的是一个随机值,这有什么用?意思是,编译器生成的默认构造函数是没有任何用处的吗?
其实啊,C++把类型分成内置类型(基本类型)和自定义类型。内置类型就是语言提供的数据类型,如:int/char...,自定义类型就是我们使用class/struct/union等自己定义的类型。
※内置类型,编译器不做处理!也就是为什么会生成随机值的原因!
※:自定义类型,会调用自定义类里面的构造函数,也就是自己的默认构造函数!做处理!
看下面代码:
class Stack
{
public:
Stack(int capacity = 4)
{
std::cout << "Stack(int capacity = 4)" << std::endl;
_a = (int*)malloc(sizeof(int) * capacity);
if (_a == NULL)
{
perror("malloc fail");
exit(-1);
}
_top = 0;
_capacity = capacity;
}
~Stack()
{
std::cout << "~Stack()"<<std::endl;
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
private:
int* _a;
int _top;
int _capacity;
};
class MyQueue
{
public:
void push(int x)
{
//;
}
private:
Stack _pushST;
Stack _popST;
int a;
};
这里面,是用栈模拟队列的类(简化版)。其中:在初始化对象的时候,由于MyQueue里面没有写构造函数,那么,MyQueue会调用默认构造函数。
而MyQueue里面有两种类型:自定义的Stack _pushST、Stack _popST 和 内置类型int a。所有,在调用默认构造函数的时候。会调用自定义类型里面的构造函数,也就是MyQueue的默认构造函数,将_pushST和_popST 初始化。而对于a不做处理,直接为随机值!
所以,我们可以:
面向需求:编译器默认生成就可以满足,就不用自己写,不满足就需要自己写
Date Stack的构造函数需要自己写
MyQueue构造函数就不需要自己写,默认生成就可以用。
注意:C++11 中针对内置类型成员不初始化的缺陷,又打了补丁,即:内置类型成员变量在
类中声明时可以给默认值。
class MyQueue
{
public:
void push(int x)
{
//;
}
private:
Stack _pushST;
Stack _popST;
int a = 10;;
};
也要注意的是:
如果同时给了构造函数和默认值,会优先使用构造函数给的值。
class Date
{
public:
Date(int year = 10, int month = 8, int day = 6)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year = 10;
int _month = 20;
int _day = 30;
};
int main()
{
Date d1;
return 0;
}
上面,一直在说着说着默认构造函数,那么默认构造函数,就一定只是指编译器默认生成的才算是默认构造函数吗?
其实不是!
无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。注意:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为是默认构造函数
为什么只能有一个?因为二义性!无参或缺省,如果在定义对象的时候,要初始化,那么要调用哪个好?
这里有个小细节:如果我们写的构造函数,不成为默认构造函数,那么如果我们在定义对象,没有去调用我们非构造函数的时候,就会出现编译器报出这样的错误:不存在默认构造函数。
为什么?那是因为,这个构造函数,既不是无参,也不是缺省,编译器也无法去生成默认的构造函数,因为已经写了一个构造函数出来了,只要有构造函数,编译器就不会去生成默认构造函数,因此,像下面的这种情况,就会报错!
3. 析构函数
3.1 概念
析构函数:与构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由
编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作。
它的功能就类似Destory......
3.2 特性
析构函数是特殊的成员函数,其特征如下:
1. 析构函数名是在类名前加上字符 ~。
2. 无参数无返回值类型。
3. 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。注意:析构函数不能重载
4. 对象生命周期结束时,C++编译系统系统自动调用析构函数
下面代码:没有初始化,也没有销毁的函数,但是有构造函数和析构函数,在对象创建的时候,已经初始化,在函数销毁的时候,已经销毁了数据结构栈的空间。
class Stack
{
public:
Stack(int capacity = 4)
{
_a = (int*)malloc(sizeof(int) * capacity);
if (_a == nullptr)
{
perror("malloc fail");
exit(-1);
}
_top = 0;
_capacity = capacity;
}
~Stack()
{
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
void Push(int x)
{
//...
_a[_top++] = x;
}
private:
int* _a;
int _top;
int _capacity;
};
int main()
{
Stack st;
st.Push(1);
st.Push(3);
st.Push(2);
return 0;
}
5.关于编译器自动生成的析构函数,是否会完成一些事情呢?下面的程序我们会看到,编译器生成的默认析构函数,对自定类型成员调用它的析构函数
class Time
{
public:
~Time()
{
std::cout << "~Time()" << std::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;
}
如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,比如Date类;有资源申请时,一定要写,否则会造成资源泄漏,比如Stack类
4. 拷贝构造函数
4.1 概念
在现实生活中,可能存在一个与你一样的自己,我们称其为双胞胎
那在创建对象时,可否创建一个与已存在对象一某一样的新对象呢?
拷贝构造函数:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用。
4.2 特征
拷贝构造函数也是特殊的成员函数,其特征如下:
1. 拷贝构造函数是构造函数的一个重载形式。
2. 拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错,因为会引发无穷递归调用
正确的用法:
class Date
{
public:
Date(int year = 10, int month = 8, int day = 6)
{
_year = year;
_month = month;
_day = day;
}
Date(Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2022, 9, 24);
Date d2(d1);
return 0;
}
错误的用法:因为在传值传参的时候,需要对实参进行拷贝成形参,在拷贝的时候,调用拷贝构造函数,再次传参传值,需要拷贝......又要拷贝......
Date(Date d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
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::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;
}
从调试来看,会进入Time的类中,调用Time的拷贝构造函数:
有个要补充的点,就是形参最好加上const!
class Date
{
public:
Date(int year, int month = 8, int day = 6)
{
_year = year;
_month = month;
_day = day;
}
//Date(Date& d)
//形参加const,防止写反了或者被修改了。!!!!
Date(const Date& d)
{
cout << "Date 拷贝构造" << endl;
_year = d._day;
_month = d._month;
_day = d._day;
}
private:
int _year = 10;
int _month = 20;
int _day = 30;
};
4. 编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式实现吗?当然像日期类这样的类是没必要的。那么下面的类呢?验证一下试试。
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(const Stack& st)//拷贝构造
{
cout << "Stack(const Stack& st)" << endl;
_a = (int*)malloc(sizeof(int) * st._capacity);
if (_a == nullptr)
{
perror("malloc fail");
exit(-1);
}
memcpy(_a, st._a, sizeof(int) * st._top);
_top = st._top;
_capacity = st._capacity;
}
在定义拷贝构造,需要开辟空间,给d2一块独立的空间才行!这样子,当d2将d1拷贝了,改变d1或d2的值也不会影响到对方,释放空间的时候,也互不影响!这才是正确的拷贝。
5. 拷贝构造函数典型调用场景:
使用已存在对象创建新对象
函数参数类型为类类型对象
函数返回值类型为类类型对象
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;
}
为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用尽量使用引用。
5.赋值运算符重载
5.1 运算符重载
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似
函数名字为:关键字operator后面接需要重载的运算符符号
函数原型:返回值类型 operator操作符(参数列表)
注意:
·不能通过连接其他符号来创建新的操作符:比如operator@
·重载操作符必须有一个类类型参数
·用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义
·作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
. * :: sizeof ? : . 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
看看下面代码:
这里会发现运算符重载成全局的就需要成员变量是公有的,那么问题来了,封装性如何保证?
class Date
{
public:
Date(int year = 1, 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(2022, 9, 22);
Date d2(2023, 1, 1);
//d1 > d2;
cout << (d1 == d2) << endl; // 转换成operator==(d1, d2);
// 也可以显示调用,一般不这样
operator==(d1, d2);
return 0;
}
这里其实可以用我们后面学习的友元解决,或者干脆重载成成员函数
bool operator==(Date* this, const Date& d2)
这里需要注意的是,左操作数是this,指向调用函数的对象
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
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(2022, 9, 22);
Date d2(2023, 1, 1);
//d1 > d2;
cout << (d1 == d2) << endl; // 转换成d1.operator==(d2);;
// 也可以显示调用,一般不这样
d1.operator==(d2);
return 0;
}
5.2 赋值运算符重载
1. 赋值运算符重载格式
参数类型:const T&,传递引用可以提高传参效率
返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值检测是否自己给自己赋值
返回*this :要符合连续赋值的含义
2. 赋值运算符只能重载成类的成员函数不能重载成全局函数:
赋值运算符重载成全局函数,注意重载成全局函数时没有this指针了,需要给两个参数
原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。
3. 用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值
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;
}
5.3 前置++和后置++重载
前置++:返回+1之后的结果
注意:this指向的对象函数结束后不会销毁,故以引用方式返回提高效率
后置++:
前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载
C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递
注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给this+1。
而temp是临时对象,因此只能以值的方式返回,不能返回引用
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
//前置++
Date& operator++()
{
_day += 1;
return *this;
}
//后置++
Date operator++(int)
{
Date temp(*this);
_day += 1;
return temp;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d;
Date d1(2022, 1, 13);
d = d1++; // d: 2022,1,13 d1:2022,1,14
d = ++d1; // d: 2022,1,15 d1:2022,1,15
return 0;
}
6.日期类的实现
①在创建返回月的天数的函数的时候,不能将数组创建在函数外,类中。因为,每次创建对象,都得开辟新的数组空间,这样很浪费空间。
②要判断年份,闰年还是平年。
class Date
{
public:
int GetMonthDay(int year, int month)
{
static int monthDayArray[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 monthDayArray[month];
}
}
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
//d1+=100
Date& operator+= (int day)
{
_day = day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month++;
if (_month == 13)
{
_year++;
_month = 1;
}
}
return *this;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2022, 9, 22);
Date d2(2022, 9, 22);
d1 += 50;
d2 += 100;
return 0;
}
7. const成员
将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改,也就是const Date* (const) this。
与一般的加const修饰不一样的是,成员函数的const是写在右边。
并且需要注意的是,不是什么成员函数都可以加上const,只有this指针指向的值不需要发生改变,那么,就可以加上const,也最好加上const。
class Date
{
public:
int GetMonthDay(int year, int month)
{
static 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(int year = 2022, int month = 10, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
bool 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 operator==(const Date& d) const
{
return _year == d._year &&
_month == d._month &&
_day == d._day;
}
bool operator<=(const Date& d) const
{
return *this < d || *this == d;
}
Date& operator++()
{
_day++;
if (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month++;
}
if (_month == 13)
{
_year++;
_month = 1;
}
return *this;
}
Date operator++(int)
{
Date ret(*this);
this->operator++();
return ret;
}
int operator-(const Date& d)
{
int count = 0;
Date i;
Date max = *this;
Date min = d;
if (*this < d)
{
max = d;
min = *this;
}
for (i = min; i < max; i++)
{
count++;
}
return count;
}
private:
int _year;
int _month;
int _day;
};
请思考下面的几个问题:
1. const对象可以调用非const成员函数吗?
2. 非const对象可以调用const成员函数吗?
3. const成员函数内可以调用其它的非const成员函数吗?
4. 非const成员函数内可以调用其它的const成员函数吗?
上面的这些问题,都是属于权限的问题。const对象不能将权限放大地去调用非const函数成员。而非const对象可以将权限缩小,去调用const成员函数。同样的,函数也是一样的道理。
8. 取地址及const取地址操作符重载
这两个默认函数一般不用自己定义,默认生成的就已经够用了。
#include<iostream>
class Date
{
public:
Date* operator&()
{
return this;
}
const Date* operator&() const
{
return this;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
std::cout << &d1 << std::endl;
return 0;
}
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如想让别人获取到指定的内容。