C++类和对象中
1.类的6个默认成员函数
如果一个类中什么成员都没有,简称为空类。
class Date {};
空类中真的什么都没有吗?并不是,任何类在什么都不写时,编译器会自动生成以下6个默认成员函数。
默认成员函数:用户没有显式实现,编译器会生成的成员函数称为默认成员函数。
2. 构造函数
2.1 概念
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.Print();
}
运行结果如图:
这段代码如果我们忘记初始化就会打印随机值,对于栈来说如果忘记初始化可能会导致程序崩溃为了应对这种情况我们可以使用构造函数来解决。
构造函数是一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,以保证每个数据成员都有 一个合适的初始值,并且在对象整个生命周期内只调用一次。
2.2 特性
构造函数是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象,而是初始化对象。
其特征如下:
- 函数名与类名相同。
- 无返回值。(不需要写void,规定)
- 对象实例化时编译器自动调用对应的构造函数。
class Date
{
public:
Date()
{
_year = 1;
_month = 1;
_day = 1;
}
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.Print();
}
运行结果如图:
- 构造函数可以重载。
class Date
{
public:
Date()
{
_year = 1;
_month = 1;
_day = 1;
}
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
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.Print();
Date d2(2024, 4, 5);
d2.Print();
}
运行结果如图:
为什么调用无参构造不加个括号呢?
既然构造函数支持重载,那么全缺省的构造函数和无参构造函数可以同时存在吗?
运行结果如图:
所以一般情况下我们只保留第二个就可以了,因为第二个在不传参数的时候包含了第一个无参构造函数的功能,一般情况,建议每个类,都可以写一个全缺省的构造。
- 如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。
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;
};
运行结果如图:
- 关于编译器生成的默认成员函数,不实现构造函数的情况下,编译器会生成默认的构造函数。但是看起来默认构造函数又没什么用?d1对象调用了编译器生成的默认构造函数,但是d1对象_year/_month/_day,依旧是随机值。也就说在这里编译器生成的默认构造函数并没有什么用吗?
解答:C++把类型分成内置类型(基本类型)和自定义类型。
内置类型就是语言提供的数据类型,如int/char/double…,
自定义类型就是我们使用class/struct/union等自己定义的类型
译器自动生成构造函数,对于内置类型成员变量,没有规定要不要处理,对于自定义类型的成员,会去调用他们的默认构造(无参构造、自动生成的构造、全缺省的构造)或者说可以不要传参就可以调用的构造函数。
class Time
{
public:
Time()
{
cout << "Time()" << endl;
_hour = 0;
_minute = 0;
_second = 0;
}
private:
int _hour;
int _minute;
int _second;
};
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;
Time _t;
};
int main()
{
Date d1;
d1.Print();
return 0;
}
调用构造函数之前
调用构造函数之后
如果对于自定义的类型会调用它对应的无参构造,如果没有无参构造就会编译报错。
class Time
{
public:
Time(int n)
{
cout << "Time()" << endl;
_hour = 0;
_minute = 0;
_second = 0;
}
private:
int _hour;
int _minute;
int _second;
};
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;
Time _t;
};
int main()
{
Date d1;
d1.Print();
return 0;
}
如图所示:
这是因为在对象实例化的时候,会给对象内部的成员变量开辟空间,所以,假如类里面的成员变量有自定义类型也会实例化这个对象,在这个对象实例化的时候就会调用这个类里面的构造函数,因为我们已经写了构造函数,所以,编译器就不会生成构造函数,就会调用我们写的构造函数,因为在实例化这个对象的时候是不传参数的,所以,如果这个构造函数实例化的时候,那么在调用这个函数的时候参数不匹配就会报错。
调用构造函数之前
调用构造函数之后
注意:C++11 中针对内置类型成员不初始化的缺陷,又打了补丁,即:内置类型成员变量在类中声明时可以给默认值。
class Date
{
public:
Date()
{
_year = 2024;
}
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "_" << _month << "_" << _day << endl;
}
private:
//声明位置给的缺省值
int _year = 1;
int _month = 1;
int _day = 1;
};
int main()
{
Date d1;
d1.Print();
return 0;
}
如果对于内置类型,没有对应的构造函数初始化这个成员变量,那么就会使用在类中声明中给这个成员变量给定的初始值。
如果我们仔细调试我们就会发现其中的猫腻,这里程序在执行的时候会先给变量赋值一个初始值,然后在自动调用这个构造函数。
运行结果如图:
- 无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。
注意:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为是默认构造函数。
总结:
- 一般情况下构造函数都需要我们显示的去实现
- 只有少数的情况下可以让编译器自动生成构造函数,类似于MyQueue,成员全是自定义类型
3.析构函数
3.1 概念
通过前面构造函数的学习,我们知道一个对象是怎么来的,那一个对象又是怎么没呢的?
析构函数:与构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作。
3.2 特性
析构函数是特殊的成员函数,其特征如下:
- 析构函数名是在类名前加上字符 ~。
- 无参数无返回值类型。
- 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。
注意:析构函数不能重载,因为析构函数没有参数 - 对象生命周期结束时,C++编译系统系统自动调用析构函数
typedef int DataType;
class Stack
{
public:
Stack(size_t capacity = 3)
{
_array = (DataType*)malloc(sizeof(DataType) * capacity);
if (NULL == _array)
{
perror("malloc申请空间失败!!!");
return;
}
_capacity = capacity;
_size = 0;
}
void Push(DataType data)
{
// CheckCapacity();
_array[_size] = data;
_size++;
}
// 其他方法...
~Stack()
{
if (_array)
{
free(_array);
_array = NULL;
_capacity = 0;
_size = 0;
}
}
private:
DataType* _array;
int _capacity;
int _size;
};
void TestStack()
{
Stack s;
s.Push(1);
s.Push(2);
}
调用析构造函数之前
调用析构造函数之后
特性5: 如果类中没有显式定义析构函数,则C++编译器会自动生成一个析构函数,一旦用户显式定义编译器将不再生成。
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;
}
运行结果如图:
6. 如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,比如Date类;有资源申请时,一定要写,否则会造成资源泄漏,比如Stack类。
实践中总结:
- 有资源需要显示清理,就需要写析构。如:Stack,List
- 有两种场景不需要显示写析构,默认生成就可以了
- 没有资源需要清理,如:Date
- 内置类型成员没有资源需要清理。剩下的都是自定义类型的成员。如:MyQueue
4. 拷贝构造函数
4.1 概念
那在创建对象时,可否创建一个与已存在对象一某一样的新对象呢?
拷贝构造函数:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用。
4.2 特征
拷贝构造函数也是特殊的成员函数,其特征如下:
- 拷贝构造函数是构造函数的一个重载形式。
- 拷贝构造函数的参数只有一个且必须是类类型(自定义类型)对象的引用,使用传值方式编译器直接报错,因为会引发无穷递归调用。
如图所示:
当我们想要把d1拷贝给d2的时候就要传参,因为这里是传值传参,所以,在传参的过程当中就要把实参d1复制给形参date,但是对于内置类型来说编译器可以直接拷贝,自定义类型的拷贝需要调用拷贝构造。
这是因为编译器完成的拷贝都是浅拷贝,只是把值一个字节一个字节的拷贝过去,对于这种日期类不会出现问题,但是当对于栈这种比较复杂的自定义类型就会有问题。
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_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;
Date d2(d1);
Date d3 = d2;//这种写法也是拷贝构造 <==> Date d3(d2)
return 0;
}
如图所示:
为什么概念里说对本类类型对象的引用一般用const修饰?有什么好处吗?
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
Date(Date& d)
{
d._day = _day;
d._month = _month;
d._year = _year;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
Date d2(d1);
Date d3 = d2;
return 0;
}
如图所示:
可以看到这里本来想把d1复制给d2,d3,但是这里都是随机值,由于我们把构造函数里面的复制写反了,就会出现这种情况,所以,加上const修饰可以避免这种情况。
实现一个函数获取X天以后的一个日期
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
Date(const Date& d)
{
cout << "Date(const Date& d)" << endl;
_year = d._year;
_month = d._month;
_day = d._day;
}
Date& GetAfterXDay(int x)
{
_day += x;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month++;
if (_month == 13)
{
_month = 1;
}
}
return *this;
}
void Print()
{
cout << _year << "年" << _month << "月" << _day << endl;
}
private:
int GetMonthDay(int year, int month)
{
int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int day = days[month];
if (month == 2 && IsLeapYear(year))
{
day++;
}
return day;
}
int IsLeapYear(int year)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
return 1;
}
return 0;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 4, 7);
Date d2 = d1.GetAfterXDay(100);
d1.Print();
d2.Print();
}
运行结果如图:
这里虽然求出来我们想要的结果,但是,我们把d1也改变了,这显然不符合我们的期待,有没有什么办法不改变d1,就可以得到我们想要的结果呢?
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
Date(const Date& d)
{
cout << "Date(const Date& d)" << endl;
_year = d._year;
_month = d._month;
_day = d._day;
}
Date GetAfterXDay(int x)
{
Date tmp = *this;
tmp._day += x;
while (tmp._day > GetMonthDay(tmp._year, tmp._month))
{
tmp._day -= GetMonthDay(tmp._year, tmp._month);
tmp._month++;
if (tmp._month == 13)
{
tmp._month = 1;
}
}
return tmp;
}
void Print()
{
cout << _year << "年" << _month << "月" << _day << endl;
}
private:
int GetMonthDay(int year, int month)
{
int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int day = days[month];
if (month == 2 && IsLeapYear(year))
{
day++;
}
return day;
}
int IsLeapYear(int year)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
return 1;
}
return 0;
}
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;
}
Date(const Date& d)
{
cout << "Date(const Date& d)" << endl;
_year = d._year;
_month = d._month;
_day = d._day;
}
// +
Date Add(int x)
{
Date tmp = *this;
tmp._day += x;
while (tmp._day > GetMonthDay(tmp._year, tmp._month))
{
tmp._day -= GetMonthDay(tmp._year, tmp._month);
tmp._month++;
if (tmp._month == 13)
{
tmp._month = 1;
}
}
return tmp;
}
// +=
Date& AddEqual(int x)
{
_day += x;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month++;
if (_month == 13)
{
_month = 1;
}
}
return *this;
}
void Print()
{
cout << _year << "年" << _month << "月" << _day << endl;
}
private:
int GetMonthDay(int year, int month)
{
int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int day = days[month];
if (month == 2 && IsLeapYear(year))
{
day++;
}
return day;
}
int IsLeapYear(int year)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
return 1;
}
return 0;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 4, 7);
Date d2 = d1.Add(100);
Date d3 = d1.Add(150);
d1.Print();
d2.Print();
d3.Print();
d1.AddEqual(200);
d1.Print();
}
对于Add函数是传值返回,返回的不是tmp,而是tmp的临时变量,但是tmp是Add函数的临时变量出了函数作用域tmp就被销毁了,所以不能传引用返回,但是对于AddEqual函数,返回的是*this,因为this指针是上一次函数栈帧里面的对象的地址,所以出了函数作用域*this不会被销毁,所以可以传引用返回减少拷贝。
运行结果如图:
3. 若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。
class Date
{
public:
Date (int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "_" << _month << "_" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 4, 7);
Date d2 = d1;
d1.Print();
d2.Print();
}
运行结果如图:
注意:在编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定义类型是调用其拷贝构造函数完成拷贝的。
- 编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式实现吗?当然像日期类这样的类是没必要的。那么下面的类呢?验证一下试试?
#include <iostream>
using namespace std;
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;
Stack s2(s1);
return 0;
}
如图所示:
当栈里面的指针指向同一块空间,销毁栈,插入,删除数据的时候两个栈都会相互影响产生错误。
什么时候需要拷贝构造?
注意:类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请时,则拷贝构造函数是一定要写的,否则就是浅拷贝。
#include <iostream>
using namespace std;
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;
}
}
Stack(const Stack& st)
{
_array = (int*)malloc(sizeof(int) * st._capacity);
if (nullptr == _array)
{
perror("malloc申请空间失败");
return;
}
memcpy(_array,st._array, st._size);
_size = st._size;
_capacity = st._capacity;
}
private:
DataType* _array;
size_t _size;
size_t _capacity;
};
int main()
{
Stack s1;
Stack s2(s1);
return 0;
}
如图所示:
如果成员都是自定义类型,内置类型没有指向资源,默认生成的拷贝构造就可以。
#include <iostream>
using namespace std;
typedef int DataType;
class Stack
{
public:
void CheckCapacity()
{
if (_size == _capacity)
{
int newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
int* ptr = (int*)realloc(_array, sizeof(int) * newcapacity);
if (ptr == nullptr)
{
perror("realloc fail");
return;
}
_array = ptr;
_capacity = newcapacity;
}
}
Stack(size_t capacity = 10)
{
_size = 0;
_capacity = capacity;
_array = (DataType*)malloc(capacity * sizeof(DataType));
if (nullptr == _array)
{
perror("malloc申请空间失败");
return;
}
}
void Push(const DataType& data)
{
CheckCapacity();
_array[_size] = data;
_size++;
}
~Stack()
{
if (_array)
{
free(_array);
_array = nullptr;
_capacity = 0;
_size = 0;
}
}
Stack(const Stack& st)
{
_size = st._size;
_capacity = st._capacity;
_array = (int*)malloc(sizeof(int) * st._capacity);
if (nullptr == _array)
{
perror("malloc申请空间失败");
return;
}
memcpy(_array,st._array, st._size);
}
private:
DataType* _array;
size_t _size;
size_t _capacity;
};
class MyQueue
{
Stack _pushst;
Stack _popst;
int size = 0;
};
int main()
{
MyQueue q1;
MyQueue q2(q1);
return 0;
}
如图所示:
- 拷贝构造函数典型调用场景:
- 使用已存在对象创建新对象
- 函数参数类型为类类型对象
- 函数返回值类型为类类型对象
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;
}
如图所示:
为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用尽量使用引用。
总结:
- 如果没有管理资源,一般情况不需要写拷贝构造,默认生成的拷贝构造就可以。如:Date
- 如果成员都是自定义类型,内置类型没有指向资源,也类似,默认生成的拷贝构造就可以。如MyQueue
- 一般情况下,不需要显示写析构函数,就不需要写拷贝构造。
- 如果内部有指针或者一些指向资源,需要显示写析构释放,通常就需要显示写构造完成深拷贝。如:Stack,Queue,List等
5.赋值运算符重载
5.1 运算符重载
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号。
函数原型:返回值类型 operator操作符(参数列表)
注意:
- 不能通过连接其他符号来创建新的操作符:比如operator@
- 重载操作符必须有一个类类型参数
- 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义
- 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
- .* :: sizeof ?: . 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
bool Equal(const Date& dt1,const Date& dt2)
{
//...
}
bool less(const Date& dt1, const Date& dt2)
{
//...
}
int main()
{
Date d1(2022, 4, 7);
Date d2(2024, 4, 8);
return 0;
}
如果我们想比较日期类的大小,我们可以写几个函数来实现,但是这样比较复杂因为关于日期类大小的比较有好几种,比如说:大于,小于,等于,大于等于,小于等于…,如果我们都把这些关系写成一个一个函数来实现名字也非常多,不太好记,那么,这时候我们就可以使用运算符重载来解决这些问题。
// 全局的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(2022, 4, 8);
Date d2(2024, 4, 8);
cout << operator==(d1, d2) << endl;
cout << (d1 == d2) << endl; //<==> operator==(d1, d2)
return 0;
}
运行结果如图:
运算符重载也可以写到类域里面
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
bool operator==(const Date& d2)
{
return _year == _year && _month == d2._month && _day == d2._day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 4, 8);
Date d2(2024, 4, 8);
cout << d1.operator==(d2) << endl;
cout << (d1 == d2) << endl; //<==> d1.operator==(d2)
return 0;
}
接下来我们实现一个小于运算符
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
bool operator==(const Date& d2)
{
return _year == _year && _month == d2._month && _day == d2._day;
}
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;
}
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 4, 7);
Date d2(2024, 4, 8);
cout << d1.operator==(d2) << endl;
cout << (d1 == d2) << endl; //<==> d1.operator==(d2)
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==(const Date& d2)
{
return _year == _year && _month == d2._month && _day == d2._day;
}
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;
}
}
bool operator<=(const Date& d)
{
return *this < d || *this == d;
}
bool operator>(const Date& d)
{
return !(*this <= d);
}
bool operator>=(const Date& d)
{
return !(*this < d);
}
bool operator!=(const Date& d)
{
return !(*this == d);
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 4, 7);
Date d2(2024, 4, 8);
cout << (d1 == d2) << endl; //<==> d1.operator==(d2)
cout << (d1 < d2) << endl;
cout << (d1 <= d2) << endl;
cout << (d1 > d2) << endl;
cout << (d1 >= d2) << endl;
cout << (d1 != d2) << endl;
return 0;
}
运行结果如图:
5.2 赋值运算符重载
- 赋值运算符重载格式
- 参数类型:const T&,传递引用可以提高传参效率
- 返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值
- 检测是否自己给自己赋值
- 返回*this :要复合连续赋值的含义
void operator=(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
运行结果如图:
但是这么没有返回值不能支持连续赋值,如果希望可以连续赋值需要增加一个返回值
//返回值为了支持连续赋值,保持运算符的特性
//d1 = d2 = d3
Date& operator=(const Date& d)
{
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
- 赋值运算符只能重载成类的成员函数不能重载成全局函数
class Date
{
public:
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;
}
// 编译失败:
// error: “operator =”必须是非静态成员
原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。
- 用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值。
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
运行结果如图:
既然编译器生成的默认赋值运算符重载函数已经可以完成字节序的值拷贝了,还需要自己实现吗?当然像日期类这样的类是没必要的。那么下面的类呢?
// 这里会发现下面的程序会崩溃掉?这里就需要我们以后讲的深拷贝去解决。
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;
}
注意:如果类中未涉及到资源管理,赋值运算符是否实现都可以;一旦涉及到资源管理则必须要实现
注意:赋值重载是针对两个已经存在的对象,用一个已经创建好的对象初始化另一个要创建的对象是复制重载。
6.日期类的实现
//Date.h
#include <iostream>
#include <assert.h>
using namespace std;
class Date
{
public:
bool CheckDate();
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in,Date& d);
Date(int year, int month = 1, int day = 1);
bool operator==(const Date& d2) 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;
void Print() const;
int GetMonthDay(int year, int month)const;
Date& operator+=(int day);
Date operator+(int day)const;
Date& operator-=(int day);
Date operator-(int day)const;
int operator-(const Date& d)const;
//++d1->d1.operator++()
Date& operator++();
//d1++->d1.operator++(0)
Date operator++(int);
Date& operator--();
Date operator--(int);
Date* operator&();
const Date* operator&() const;
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);
//Date.cpp
#include "Date.h"
Date::Date(int year , int month, int day)
{
_year = year;
/*if ((month > 0 && month < 13) && day > 0 && day <= GetMonthDay(year, month))
{
_month = month;
_day = day;
}
else
{
cout << "日期非法" << endl;
}*/
_month = month;
_day = day;
if (!CheckDate())
{
cout << "日期非法" << endl;
exit(-1);
}
}
bool Date::operator==(const Date& d2) const
{
return _year == d2._year && _month == d2._month && _day == d2._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;
}
else
{
return false;
}
}
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);
}
void Date::Print() const
{
cout << _year << "/" << _month << "/" << _day << endl;
}
int Date::GetMonthDay(int year, int month) const
{
assert(month > 0 && month < 13);
static 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;
}
else
{
return monthArray[month];
}
}
//Date& Date::operator+=(int day)
//{
// _day += day;
// while (_day > GetMonthDay(_year, _month))
// {
// _day -= GetMonthDay(_year, _month);
// _month++;
//
// if (_month == 13)
// {
// _year = 1;
// _month--;
// }
// }
//
// 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._month = 1;
tmp._year++;
}
}
return tmp;
}
//Date Date::operator+(int day)
//{
// Date tmp = *this;
//
// tmp += day;
//
// return tmp;
//}
Date& Date::operator+=(int day)
{
if (day < 0)
{
return *this -= -day;
}
*this = *this + day;
return *this;
}
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;
}
int Date::operator-(const Date& d) const
{
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;
}
Date& Date::operator++()
{
*this += 1;
return *this;
}
Date Date::operator++(int)
{
Date tmp = *this;
*this += 1;
return tmp;
}
Date& Date::operator--()
{
*this -= 1;
return *this;
}
Date Date::operator--(int)
{
Date tmp = *this;
*this += 1;
return tmp;
}
ostream& operator<<(ostream& out, const Date& d)
{
out << d._year << "年" << d._month << "月" << d._day << endl;
return out;
}
bool Date::CheckDate()
{
if (_month < 1 || _month > 12 || _day < 1 || _day > GetMonthDay(_year, _month))
{
return false;
}
return true;
}
istream& operator>>(istream& in,Date& d)
{
cout << "请依次输入年月日:>";
in >> d._year >> d._month >> d._day;
if (!d.CheckDate())
{
cout << "日期非法" << endl;
exit(-1);
}
return in;
}
Date* Date::operator&()
{
return this;
}
const Date* Date::operator&() const
{
return this;
}
7.const成员
将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。
class Date
{
public:
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << "Print()" << endl;
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl << endl;
}
void Print() const
{
cout << "Print()const" << endl;
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl << endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
运行结果如图:
class Date
{
public:
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << "Print()" << endl;
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl << endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
如图所示:
总结:只读对象可以加const,内部不涉及修改生成,这样cosnt对象,非cosnt对象都可以调用
8.取地址及const取地址操作符重载
这两个默认成员函数一般不用重新定义 ,编译器默认会生成。
class Date
{
public:
Date* operator&()
{
return this;
}
const Date* operator&()const
{
return this;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如想让别人获取到指定的内容!