第三章:类与对象中
3.1类的6个默认成员函数
1.默认成员函数:
我们不写,编译器也会自动生成的函数(空类并不空)。
2. 6个默认成员函数:
1)初始化和清理
- 构造函数主要完成初始化工作。
- 析构函数主要完成清理工作。
2)拷贝复制:
- 拷贝构造是使用类对象初始化创建对象
- 赋值重载主要是把一个对象赋值给另一个对象
3)取地址重载
主要是普通对象和const对象取地址,这两个很少会自己实现。
3.2构造函数
1.概念:
构造函数是一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,以保证每个数据成员都有一个合适的初始值,并且在对象整个生命周期内只调用一次。
2.特性:
1)构造函数是特殊的成员函数,需注意:
- 构造函数的主要任务不是开空间创建对象,而是初始化对象(调用函数,建立栈帧时就已经开辟好了空间)。
2)构造函数特征如下:
- 函数名与类名相同。
- 无返回值(也不用写void)。
- 对象实例化时编译器自动调用对应的构造函数。
- 构造函数可以重载。
class Date
{
public:
//成员函数
//构造函数(初始化)
//1.无参构造函数
Date() //名字与类名相同
{
_year = _month = _day = 0;
}
//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;
};
int main()
{
Date A;
A.print();
//报错,构造函数对同一个变量只能使用一次
/*Date A(1, 1, 1);
A.print();*/
//不传参初始化不能这样写
//Date A();
//因为编译器不知道这是函数声明,还是变量的声明
//利用构造函数初始化
Date B(2004, 8, 21);
B.print();
return 0;
}
输出结果:
0 0 0
2004 8 21
注意:
那两个Date函数可以合并成一个全缺省的函数,而且更灵活了(可以只传年,也可以只传年月)。
代码:
class Date
{
public:
Date(int year = 0, int month = 0, int day = 0)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2003); //只给年
Date d2(2003, 1); //给年给月
Date d3(2003, 5, 2); //给年月日
return 0;
}
C++中的栈(使用了构造函数):
//SeqStack.h头文件
#pragma once
//头文件
#include<iostream>
#include<assert.h>
//展开命名空间
using namespace std;
typedef int STDataType;
//栈的类型定义
class Stack
{
//成员函数
public:
//构造函数
Stack(int capacity = 4) //给缺省值,如果什么也不传,就默认开辟4个数据的空间
{
if (capacity == 0)
{
_a = nullptr;
_top = _capacity = 0;
}
else
{
STDataType* tmp = (STDataType*)malloc(sizeof(STDataType) * capacity);
if (tmp == nullptr)
{
perror("malloc fail\n");
exit(-1); //程序退出,返回-1
}
_a = tmp;
_top = 0;
_capacity = capacity;
}
}
//销毁
void Destory();
//栈顶插入删除数据
//入栈
void Push(STDataType x);
//出栈
void Pop();
//取栈顶数据
STDataType Top();
//计算栈的大小
int Size();
//判断栈是否为空,是就返回真,不是就返回假
bool Empty();
private:
//检查容量,不够扩容
void CheckCapacity(); //检查容量的这个函数用户不需要使用
//成员变量
private:
STDataType* _a;
int _top;
int _capacity;
};
//.cpp函数实现文件
#include"SeqStack.h"
//检查容量,不够扩容
void Stack::CheckCapacity()
{
if (_capacity == _top)
{
STDataType* tmp = (STDataType*)realloc(_a, sizeof(STDataType) * _capacity * 2);
if (tmp == nullptr)
{
perror("realloc fail\n");
return;
}
_a = tmp;
_capacity *= 2;
cout << "realloc succeed\n" << endl;
}
}
//销毁
void Stack::Destory()
{
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
//栈顶插入删除数据
//入栈
void Stack::Push(STDataType x)
{
//先检查是否要扩容
CheckCapacity();
//放数据
_a[_top] = x;
_top++;
}
//出栈
void Stack::Pop()
{
assert(_top > 0);
_top--;
}
//取栈顶数据
STDataType Stack::Top()
{
assert(_top > 0);
return _a[_top - 1];
}
//计算栈的大小
int Stack::Size()
{
return _top;
}
//判断栈是否为空,是就返回真,不是就返回假
bool Stack::Empty()
{
return _top == 0;
}
#include"SeqStack.h"
int main()
{
cout << "st1:" << endl;
Stack st1; //这里其实也调用了构造函数,没有参数,默认容量是缺省值4
st1.Push(1);
st1.Push(2);
st1.Push(3);
st1.Push(4);
st1.Push(5);
while (!st1.Empty())
{
cout << st1.Top() << endl;
st1.Pop();
}
st1.Destory();
cout << "st2:" << endl;
Stack st2(100); //调用构造函数初始化,需要100个空间,就传100
for (size_t i = 1; i <= 100; i++)
{
st2.Push(i);
}
while (!st2.Empty())
{
cout << st2.Top() << endl;
st2.Pop();
}
st2.Destory();
return 0;
}
3.如果类中没有显示定义构造函数,C++编译器会自动生成一个无参的默认构造函数。
1)编译器生成的默认构造函数的特点:
-
1.我们不写才会生成,写了任意一个构造函数就不会生成了。
再想以使用无参的形式使用默认构造函数时,报错。
说明我们只要自己写了构造函数,编译器就不会再自动生成了。 -
2.内置类型的成员不做处理(C++11,声明支持给缺省值,指针全是内置类型)。
内置类型的成员不做处理,祖师爷后悔了。
private:
//成员变量
//声明支持给缺省值,相当于给默认生成的构造函数传参了
int _year; //不给year缺省值,发现year是随机值(内置类型默认构造函数不做处理)
int _month = 2;
int _day = 2;
int main()
{
Date a; //在此处调用构造函数
a.print();
return 0;
}
注意:有的编译器也会自己处理,这是因为编译器越来越聪明了,会自己填坑了。
- 3.自定义类型的成员才会处理,处理方式是回去调用这个成员的默认构造函数(如果没有默认构造函数,直接报错,因为间接调用无法传参)。
我们在日期类中声明了一个时间类变量:
private:
//成员变量
//声明支持给缺省值,相当于给默认生成的构造函数传参了
int _year; //不给year缺省值,发现year是随机值(内置类型默认构造函数不做处理)
int _month = 2;
int _day = 2;
Time _time; //自定义类型,回去调用这个类的构造函数
}
class Time
{
public:
//成员函数
Time()
{
_hour = 1;
_minute = 1;
_second = 1;
}
void print()
{
cout << "time:" << _hour << " " << _minute << " " << _second << endl;
}
private:
//成员变量
int _hour;
int _minute;
int _second;
};
- 4.代码:(上面例子的代码整合)
class Time
{
public:
//成员函数
Time()
{
_hour = 1;
_minute = 1;
_second = 1;
}
void print()
{
cout << "time:" << _hour << " " << _minute << " " << _second << endl;
}
private:
//成员变量
int _hour;
int _minute;
int _second;
};
class Date
{
public:
//成员函数
/*Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}*/
//如果放开这一段代码,将不再自动生成构造函数
/*Date(int year, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}*/
//半缺省参数,来验证性质1
void print()
{
cout << "Date:" << _year << " " << _month << " " << _day << endl;
_time.print();
}
private:
//成员变量
//声明支持给缺省值,相当于给默认生成的构造函数传参了
int _year; //不给year缺省值,发现year是随机值(内置类型默认构造函数不做处理)
int _month = 2;
int _day = 2;
Time _time; //自定义类型,回去调用这个类的构造函数
public:
Time* _ptime; //指针都是内置类型
};
int main()
{
Date a; //在此处调用构造函数
a.print();
cout << a._ptime << endl;
return 0;
}
//默认构造函数的三个性质:
//我们不写才会生成,写了任意一个构造函数就不会生成了
//内置类型的成员不会处理(C++11,声明支持给缺省值,指针全是内置类型)
//自定义类型的成员才会处理,处理方式是回去调用这个成员的构造函数
4.无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。
- 注意:
无参构造函数、全缺省构造函数、我们没写编译器生成的构造函数,都可以认为是默认构造函数。
5.总结:
- 默认构造函数不传参就可以调用。
- 多个并存会存在二义性。
3.3析构函数
1.概念:
- 与构造函数功能相反,析构函数不是完成对象本身的销毁,局部对象销毁工作是由编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作。
2.特性:
- 析构函数名是在类名前加上字符~。
- 无参数无返回值类型。
- 一个类只能有一个析构函数。若未显示定义,系统会自动生成默认的析构函数。注意:
析构函数不能重载(很好理解,因为没有参数,构不成重载,所以析构函数是唯一的)。
- 对象生命周期结束时(出作用域),C++编译系统自动调用析构函数。
思考析构函数调用的顺序问题:a,b先调用谁的析构函数?
先调用b的,函数实现利用栈帧,有栈后进先出的性质,所以b的析构函数先调用(可以通过调试,查看this指针的变化来验证)。
- 编译器自动生成的默认析构函数的特点:
内置类型成员不做处理。
自定义类型成员会调用这个成员的析构函数。
3.看代码:
- 上边的代码整合(这段代码只是介绍析构函数,没有实际意义):
class Time
{
public:
Time()
{
_hour = 0;
_minute = 0;
_second = 0;
}
~Time()
{
cout << "~Time()" << endl;
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
public:
//成员函数
Date(int year = 0, int month = 0, int day = 0)
{
_year = year;
_month = month;
_day = day;
}
//析构函数
~Date() //无参数,无返回值
{
cout << "~Date()" << endl;
}
//日期类的析构函数没有意义,因为日期类型的变量出了函数作用域后自动销毁
private:
//成员变量
int _year;
int _month;
int _day;
Time _time; //自定义成员,调用这个成员的析构函数
};
int main()
{
Date a; //思考a,b析构函数调用的顺序
Date b;
return 0;
}
- 一个有意义的析构函数:
//一个有意义的析构函数
typedef int DataType;
class Stack
{
public:
~Stack()
{
free(_array);
_array = nullptr;
}
private:
DataType* _array;
int _top;
int _capacity;
};
4.分析析构函数的优势:
- 括号匹配实现(左边是C语言,右边是C++)
1)C语言中,在return false和最后返回ret处,都要记得销毁栈,有时难免会忘记。
2)C++中,有了析构函数,编译器会自动销毁栈,即使忘记也没有关系。
5.C++中的栈:(使用了构造函数和析构函数)
//头文件
#include<iostream>
#include<assert.h>
//展开命名空间
using namespace std;
typedef int STDataType;
//栈的类型定义
class Stack
{
//成员函数
public:
//构造函数
Stack(int capacity = 4) //给缺省值,如果什么也不传,就默认开辟4个数据的空间
{
if (capacity == 0)
{
_a = nullptr;
_top = _capacity = 0;
}
else
{
STDataType* tmp = (STDataType*)malloc(sizeof(STDataType) * capacity);
if (tmp == nullptr)
{
perror("malloc fail\n");
exit(-1); //程序退出,返回-1
}
_a = tmp;
_top = 0;
_capacity = capacity;
}
}
//销毁
~Stack()
{
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
//栈顶插入删除数据
//入栈
void Push(STDataType x)
{
//先检查是否要扩容
CheckCapacity();
//放数据
_a[_top] = x;
_top++;
}
//出栈
void Pop()
{
assert(_top > 0);
_top--;
}
//取栈顶数据
STDataType Top()
{
assert(_top > 0);
return _a[_top - 1];
}
//计算栈的大小
int Size() { return _top; }
//判断栈是否为空,是就返回真,不是就返回假
bool Empty() { return _top == 0; }
private:
//检查容量,不够扩容
void CheckCapacity() //检查容量的这个函数用户不需要使用
{
if (_capacity == _top)
{
STDataType* tmp = (STDataType*)realloc(_a, sizeof(STDataType) * _capacity * 2);
if (tmp == nullptr)
{
perror("realloc fail\n");
return;
}
_a = tmp;
_capacity *= 2;
cout << "realloc succeed\n" << endl;
}
}
//成员变量
private:
STDataType* _a;
int _top;
int _capacity;
};
int main()
{
cout << "st1:" << endl;
Stack st1; //这里其实也调用了构造函数,没有参数,默认容量是缺省值4
st1.Push(1);
st1.Push(2);
st1.Push(3);
st1.Push(4);
st1.Push(5);
while (!st1.Empty())
{
cout << st1.Top() << endl;
st1.Pop();
}
cout << "st2:" << endl;
Stack st2(100); //调用构造函数初始化,需要100个空间,就传100
for (size_t i = 1; i <= 100; i++)
{
st2.Push(i);
}
while (!st2.Empty())
{
cout << st2.Top() << " ";
st2.Pop();
}
cout << endl;
return 0;
}
3.4拷贝构造函数
1.概念
只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用。
1)来看一段代码,看看这样拷贝是否行的通:
class Date
{
public:
//成员函数
Date(int year = 0, int month = 0, int day = 0)
{
_year = year;
_month = month;
_day = day;
}
void print()
{
cout << _year << " " << _month << " " << _day << endl;
}
private:
//成员变量
int _year;
int _month;
int _day;
};
Date Func(Date d)
{
return d;
}
int main()
{
Date d1(2022, 4, 7);
Date d2 = Func(d1);
d2.print();
return 0;
}
输出:
2022 4 7
拷贝成功。
2)但是如果用同样的方式来复制栈,就会出问题,来看代码:
typedef int STDataType;
//栈的类型定义
class Stack
{
//成员函数
public:
//构造函数
Stack(int capacity = 4) //给缺省值,如果什么也不传,就默认开辟4个数据的空间
{
if (capacity == 0)
{
_a = nullptr;
_top = _capacity = 0;
}
else
{
STDataType* tmp = (STDataType*)malloc(sizeof(STDataType) * capacity);
if (tmp == nullptr)
{
perror("malloc fail\n");
exit(-1); //程序退出,返回-1
}
_a = tmp;
_top = 0;
_capacity = capacity;
}
}
//销毁
~Stack()
{
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
//栈顶插入删除数据
//入栈
void Push(STDataType x)
{
//先检查是否要扩容
CheckCapacity();
//放数据
_a[_top] = x;
_top++;
}
//出栈
void Pop()
{
assert(_top > 0);
_top--;
}
//取栈顶数据
STDataType Top()
{
assert(_top > 0);
return _a[_top - 1];
}
//计算栈的大小
int Size() { return _top; }
//判断栈是否为空,是就返回真,不是就返回假
bool Empty() { return _top == 0; }
private:
//检查容量,不够扩容
void CheckCapacity() //检查容量的这个函数用户不需要使用
{
if (_capacity == _top)
{
STDataType* tmp = (STDataType*)realloc(_a, sizeof(STDataType) * _capacity * 2);
if (tmp == nullptr)
{
perror("realloc fail\n");
return;
}
_a = tmp;
_capacity *= 2;
cout << "realloc succeed\n" << endl;
}
}
//成员变量
private:
STDataType* _a;
int _top;
int _capacity;
};
//拷贝
Stack fun2(Stack s)
{
return s;
}
int main()
{
cout << "s1:" << endl;
Stack s1; //这里其实也调用了构造函数,没有参数,默认容量是缺省值4
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
s1.Push(5);
Stack s2 = fun2(s1); //直接报错
return 0;
}
这样的拷贝方式我们称为浅拷贝。(就是形参和实参中的指针指向同一个空间)
分析:
看一张图
首先s1是在main函数的栈帧中的,在执行函数fun2时,首先为函数fun2创建了栈帧,然后再将s1中的全部数据拷贝给了形参s,包括指针_a,栈顶_top,容量_capacity。在出函数fun2时,形参s首先执行自己的析构函数,将_a标记的空间全部释放了。在main函数结束时,又执行了s1的析构函数,由释放了一次_a。注意,两次释放同一个空间,程序直接就报错了。(这也是C语言中的一个坑)
验证:
我们来查看一下s1,和s的_a指针分别指向哪里:
发现s1,和s的_a指针是指向同一块空间的。
3)解决方法:C++引入了一个新的函数,拷贝构造。
Date类的拷贝构造函数:
class Date
{
public:
//成员函数
Date(int year = 0, int month = 0, int day = 0)
{
_year = year;
_month = month;
_day = day;
}
//拷贝构造
//注意:不能写成Date(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(2023, 8, 1);
//拷贝构造函数的使用,下面两个写法相等
Date d2(d1);
Date d3 = d1;
return 0;
}
栈的拷贝构造函数:
//栈的拷贝构造函数
Stack(Stack& s)
{
//深拷贝
//开辟新空间
STDataType* tmp = (STDataType*)malloc(sizeof(STDataType) * s._capacity);
if (!tmp)
{
perror("malloc fail\n");
exit(-1);
}
_a = tmp;
//拷贝数据
memcpy(_a, s._a, sizeof(STDataType) * s.Size());
_capacity = s._capacity;
_top = s._top;
}
使用:
int main()
{
Stack st1(100);
Stack st2(st1);
Stack st3 = st2;
return 0;
}
2.特征
1.拷贝构造函数是构造函数的一个重载形式。
2.拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错,会引发无穷递归调用。
C++在传自定义类型的参数时,会先调用一次拷贝构造,以解决浅拷贝的问题。
就是说,func1中传自定义类型参数d1,编译器会去调用一下Date类的拷贝构造函数,以这种方式给形参d赋值。
但是如果拷贝构造函数的参数是类类型对象(传值),就会引发无穷递归。
Date d2(d1);
这句代码表示调用拷贝构造,将d1拷贝给d2。然而编译器在调用拷贝构造函数时,发现函数是以传值方式调用的,又去拷贝构造函数以赋值形参,然而这个过程又调用了拷贝构造函数,进而引发了无穷递归。(编译器会检查无穷递归,发现会直接报错,不会死循环)。
3.若未显示定义,编译器会生成默认的拷贝构造函数。默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。
默认生成的拷贝构造函数的特点:
1)对内置类型的参数,进行值拷贝。
2)对自定义类型的参数,调用这个自定义类型的拷贝构造函数。
总结:
1)Date类不需要我们实现拷贝构造,默认生成的就可以用。
2)Stack需要我们实现拷贝构造,直接使用默认生成的会出问题。
MyQueue的红利:
class MyQueue
{
private:
Stack _pushst;
Stack _popst;
};
int main()
{
//不用写构造函数和析构函数
MyQueue mq1;
//也不用写拷贝构造
MyQueue mq2 = mq1;
return 0;
}
注意:传引用传参如果不是为了改变实参,最好加上const修饰。(拷贝构造一般都加const)
class Date
{
public:
//成员函数
//拷贝构造:
Date(const Date& d) //权限的缩小
{
_year = d._year;
_month = d._month;
_day = d._day;
}
//以免出现下面的写法
/*Date(Date& d)
{
d._year = _year;
d._month = _month;
d._day = _day;
}*/
//即没有完成拷贝,也弄丢了原来的数据
private:
//成员变量
int _year;
int _month;
int _day;
};
4.拷贝构造函数典型调用场景:
1)使用已存在对象创建新对象。
2)函数参数类型为类类型对象。
3)函数返回值类型为类类型对象。
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.总结:
类中如果没有涉及资源申请时,拷贝构造函数写不写都可以;一旦涉及到资源申请时,则拷贝构造函数是一定要写的,否则就是浅拷贝。
3.5赋值运算符重载
引入:
我们知道,2023年7月20号,是在2023年8月1号之前的,我们想用一个简单的运算符<
来表示这样的关系(一个日期在另一个日期之前)。
但是,这样的代码显然是错误的:
class Date
{
//...
}
int main()
{
Date d1(2023, 7, 20);
Date d2(2023, 8, 1);
d1 < d2; //报错
return 0;
}
那么,我们该如何实现这样的功能呢?请看接下来运算符重载的表演。
3.5.1运算符重载
1.概念:
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号。
函数原型:返回值类型 operator操作符(参数列表)
2.相关重载的实现:
1)实现日期类的<
:
在主函数中定义:
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;
};
//注意:要想这样定义函数,一个最暴力的方法是把private注释掉,会出问题
bool operator<(const Date& d1, const Date& d2)
{
if (d1._year < d2._year)
{
return true;
}
else if (d1._year == d2._year && d1._month < d2._month)
{
return true;
}
else if (d1._year == d2._year && d1._month == d2._month && d1._day < d2._year)
{
return true;
}
else
{
return false;
}
}
int main()
{
Date d1(2023, 7, 20);
Date d2(2023, 8, 1);
cout << (d1 < d2) << endl;
cout << (operator<(d1, d2)) << endl; // 显示写
//注意不能写成:
//cout << d1 < d2 << endl;
//因为<<的优先级比<高
return 0;
}
在类中定义:(作为类成员函数重载时,其形参看起来比实际操作数少1个,因为成员函数的第一个参数为隐藏的this)
class Date
{
public:
//成员函数
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// 这里实际上是:d1.operator<(d2)
bool operator<(const Date& d2)
{
// 这里把this显示的写出来了,方便理解,今后就不会显示写了
if (this->_year < d2._year)
{
return true;
}
else if (this->_year == d2._year && this->_month < d2._month)
{
return true;
}
else if (this->_year == d2._year && this->_month == d2._month && this->_day < d2._day)
{
return true;
}
else
{
return false;
}
}
private:
//成员变量
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2023, 7, 20);
Date d2(2023, 8, 1);
cout << (d1 < d2) << endl;
cout << d1.operator<(d2) << endl; //显示写
return 0;
}
2)实现==
:(下面这些函数都定义在类中)
bool operator==(const Date& d)
{
return _year == d._year && _month == d._month && _day == d._day;
}
3)实现<=
:
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;
}
3)实现>
:
bool operator>(const Date& d)
{
return !(*this <= d);
}
4)实现>=
:
bool operator>=(const Date& d)
{
return !(*this < d);
}
5)实现!=
:
bool operator!=(const Date& d)
{
return !(*this == d);
}
6)实现+=
:
为了实现这个重载,我们还要实现一个函数GetMonthDay()
来获取当前年的当前月的天数。
int GetMonthDay()
{
//定义13个空间,一一对应,二月先给28天
int monthArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
//闰年的2月有29天
if (_month == 2 && ((_year % 4 == 0 && _year % 100 != 0) || (_year % 400 == 0)))
{
return 29;
}
//这里最好把month == 2放在最前面判断,因为如果不是2月,就不用判断是不是闰年了
return monthArray[_month];
}
Date& operator+=(int day)
{
_day += day;
while (_day > this->GetMonthDay())
{
_day -= this->GetMonthDay();
// 日满了,月进位
++_month;
// 月满了,年进位
if (_month == 13)
{
++_year;
_month = 1; //月归1
}
}
return *this; //d1一直都在,可以用传引用返回,提高效率
}
主函数:
int main()
{
Date d1(2023, 7, 20);
Date d2(2023, 8, 1);
d1 += 20;
d1.print();
return 0;
}
7)实现+
:
Date operator+(int day)
{
Date tmp = *this; //用tmp来拷贝d1,因为我们不希望改变d1
tmp._day += day;
while (tmp._day > tmp.GetMonthDay())
{
tmp._day -= tmp.GetMonthDay();
// 日满了,月进位
++tmp._month;
// 月满了,年进位
if (tmp._month == 13)
{
++_year;
tmp._month = 1; //月归1
}
}
return tmp; //tmp出了作用域消失,不能用传引用返回
}
复用+=
:
Date operator+(int day)
{
Date tmp(*this);
tmp += day;
return tmp;
}
主函数:
int main()
{
Date d1(2023, 7, 20);
Date d2(2023, 8, 1);
cout << (d1 < d2) << endl;
//cout << (operator<(d1, d2)) << endl; // 显示写
cout << d1.operator<(d2) << endl; //显示写
cout << (d1 == d2) << endl;
cout << (d1 <= d2) << endl;
//注意不能写成:
//cout << d1 < d2 << endl;
//因为<<的优先级比<高
cout << (d1 > d2) << endl;
cout << (d1 >= d2) << endl;
cout << (d1 != d2) << endl;
Date d3 = d1 + 50;
d3.print();
d3 += 20;
d3.print();
return 0;
}
3.总结:
注意:
1)不能通过连接其他符号来创建新的操作符:比如
operator@
。2)重载操作符必须有一个类类型参数。(下面的例子是定义在全局的,只有两个参数都是int,是一个错误示范)例:
bool operator<(int x, int y);
3)用于内置类型的运算符,其含义不能改变,例如:内置的整型
+
,不能改变其含义。(跟3的例子差不多,我们不能改变用于两个整型的+
的含义)
int operator+(int x, int y);
4)作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this。
5).* :: sizeof ?: .
注意以上几个操作符不能重载。(.*
很少用到,几乎见不到,?:
是三目运算符)
3.5.2赋值运算符重载
1.赋值运算符重载格式:
1)参数类型:const T&,传递引用可以提高传参效率。
2)返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值。
3)检测是否自己给自己赋值(不能自己给自己赋值)。
4)返回*this:支持连续赋值。
先看一个错误示范:(这些函数定义在类中)
// 声明和定义分离写
void Date::operator=(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
主函数:
int main()
{
Date d1(2023, 7, 27);
Date d2;
Date d3;
d2 = d1; // 可以编过
d3 = d2 = d1; // 不能编过
return 0;
}
分析:我们知道,d2 = d1
这段代码,会被编译器看做d2.operator(d1)
,一个函数;如果想实现连续赋值,需要让这个函数的返回值也是d1对应的值,而我们这样写赋值函数,返回类型是空,当然编不过。返回类型其实可以是Date,但是为了效率考虑,选择使用Date&,因为这样就不会在函数返回时,再创建临时变量了。
正确写法:(支持连续赋值)
Date& Date::operator=(const Date& d)
{
// 判断是不是自己给自己赋值
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
2.赋值运算符只能重载成类的成员函数,不能重载成全局函数:
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 C2801: “operator =”必须是非静态成员
原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。
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;
}
下面这段代码如果使用默认的赋值重载会出问题:
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;
}
这就涉及了浅拷贝和深拷贝的问题,我们以后会细讲,在此先提一下:
1)浅拷贝:只是拷贝了源对象的地址,所以源对象的任何值发生改变时,拷贝对象的值也会随之而发生变化。在这里,s1的
_array
复制给了s2的_array
,二者指向的是同一块空间,在程序结束时,调用s1和s2的析构函数,释放两次_array
所指向的空间,直接报错。
2)深拷贝:则是拷贝了源对象的所有值而不是地址,所以即使源对象的值发生任何变化时,拷贝对象的值也不会改变。
4.前置++和后置++:
采用复用+=
的方式实现:
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;
}
// 后置++:
// 前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载
// C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递
// 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给this+1
// 而temp是临时对象,因此只能以值的方式返回,不能返回引用
Date operator++(int)
{
Date temp(*this);
_day += 1;
return temp;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2023, 8, 7);
Date d2(2023, 8, 7);
// 下面两个写法等效
d1++;
d1.operator++(100); // 这里传几都无所谓,只要是个整数就行
// 下面两个写法等效
++d2;
d2.operator++();
return 0;
}
注意:(前置++和后置++函数名的区别)
1)前置++:
Date& operator++()
传引用返回,不需要另传参数。
2)后置++:Date operator++(int)
传值返回,需要另写一个参数int
。
3.6完整的日期类
1.头文件Date.h
class Date
{
public:
//成员函数
//构造函数
Date(int year = 1, int month = 1, int day = 1);
//打印
void Print();
//获取当前月的天数
int GetMonthDay(int year, int month);
/*void operator=(const Date& d);*/
Date& operator=(const Date& d);
Date& operator+=(int day);
Date operator+(int day);
Date& operator-=(int day);
Date operator-(int day);
bool operator<(const Date& d);
bool operator==(const Date& d);
bool operator!=(const Date& d);
bool operator<=(const Date& d);
bool operator>(const Date& d);
bool operator>=(const Date& d);
// ++d
// d++
// 函数重载
// 运算符重载
// ++d1 -> d1.operator++()
Date& operator++();
// d1++ -> d1.operator++(0)
// 加一个int参数,进行占位,跟前置++构成函数重载进行区分
// 本质是后置++调用,编译器进行了特殊处理
Date operator++(int);
Date& operator--();
Date operator--(int);
int operator-(const Date& d);
private:
//成员变量
int _year;
int _month;
int _day;
};
2.函数实现文件Func.cpp
#include"Date.h"
Date::Date(int year, int month, int day)
{
//判断日期是否合法
if (year < 1 || month < 1 || month > 12 || day < 1 || day > GetMonthDay(year, month))
{
cout << "Date error" << endl;
// exit(-1);
}
_year = year;
_month = month;
_day = day;
}
void Date::Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
//获取当前月的天数
int Date::GetMonthDay(int year, int month)
{
//相关优化
const static int monthArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 1 2 3 4 5 6 7 8 9 10 11 12
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
{
return 29;
}
return monthArray[month];
}
//错误写法
//void Date::operator=(const Date& d) //这里也可以不加&,只不过用传引用的方式效率更高
//{
// _year = d._year;
// _month = d._month;
// _day = d._day;
//}
Date& Date::operator=(const Date& d)
{
// 判断是不是自己给自己赋值
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
Date& Date::operator+=(int 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)
{
Date tmp = *this;
tmp += day;
return tmp;
}
Date& Date::operator-=(int day)
{
_day -= day;
while (_day <= 0)
{
_month--;
if (_month == 0)
{
_year--;
_month = 12;
}
_day += GetMonthDay(_year, _month); //借的是前一个月的天数
}
return *this;
}
Date Date::operator-(int day)
{
Date tmp = *this;
tmp -= day;
return tmp;
}
bool Date::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 Date::operator==(const Date& d)
{
return _year == d._year && _month == d._month && _day == d._day;
}
bool Date::operator!=(const Date& d)
{
return !(*this == d);
}
bool Date::operator<=(const Date& d)
{
return *this < d || *this == d;
}
bool Date::operator>(const Date& d)
{
return !(*this <= d);
}
bool Date::operator>=(const Date& d)
{
return !(*this < d);
}
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 *this;
}
int Date::operator-(const Date& d)
{
// 默认是左大右小
Date max = *this;
Date min = d;
int flag = 1; // flag来控制符号
// 处理左小右大的情况
if (*this < d)
{
max = d;
min = *this;
flag = -1;
}
// 小的日期不断++,直到和大日期相等,加了多少次,就是差了多少天
int n = 0;
while (min != max) // 这里不建议用<判断,因为<的实现比较复杂
{
++min;
++n;
}
return n * flag;
}
3.优化GetMonthDay()
函数:
//获取当前月的天数
int Date::GetMonthDay(int year, int month)
{
//相关优化
const static int monthArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 1 2 3 4 5 6 7 8 9 10 11 12
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
{
return 29;
}
return monthArray[month];
}
1)使用了const
和static
修饰数组,让数组不能被改变,获得常属性。同时数组经过static
修饰,出了函数也不会被销毁,不会有栈帧创建和销毁的时间损耗,节省了时间。
2)在判断是否是闰年的二月时先判断是不是二月,如果不是,根据短路原理,就不会进行后面的判断了,也节省了时间。
4.日期相减函数int operator-(const Date& d)
:
int Date::operator-(const Date& d)
{
// 默认是左大右小
Date max = *this;
Date min = d;
int flag = 1; // flag来控制符号
// 处理左小右大的情况
if (*this < d)
{
max = d;
min = *this;
flag = -1;
}
// 小的日期不断++,直到和大日期相等,加了多少次,就是差了多少天
int n = 0;
while (min != max) // 这里不建议用<判断,因为<的实现比较复杂
{
++min;
++n;
}
return n * flag;
}
3.7const成员
1.引入:
看一段有问题的代码:
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()
{
const Date d1; // const修饰的自定义类型变量
d1.print(); // 报错,为什么?
return 0;
}
思考:为什么会报错呢?
因为this指针的类型是
类型* const
,而void print()
这段代码把this指针显示的写就是void print(Date* const this)
,this是不可以改的,但是*this是可以改的,也就是说自定义类型变量中的内容是可以改的。然而,我们的d1是经过const修饰的,这就意味着d1不能改变,*this是可以改变的,我们可以通过*this来改变d1,本质上是一种权限放大,是不被允许的。
正确写法:
class Date
{
public:
//成员函数
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// 这种写法是规定,记住就行,用于接收const修饰的自定义类型变量
void print() const
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
//成员变量
int _year;
int _month;
int _day;
};
int main()
{
const Date d1; // const修饰的自定义类型变量
d1.print(); // 报错
return 0;
}
分析:void print() const;
这段代码,如果显示的把this指针写出来,就是void print(Date const * const this);
。既不能改变this,也不能改变*this,属于权限的平移。
2.概念:
将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。
3.看几个问题:
1)问题1:
// 思考这样的写法有什么意义
const int func()
{
int ret = 1;
return ret;
}
没有任何意义,因为这是一个传值返回,函数结束时会先把ret的值存在一个临时变量中,这个临时变量是具有常属性的,加不加const
都一样。
// 这样写就有意义了
const int& func()
{
static int ret = 1;
return ret;
}
ret被static
修饰,函数结束时不销毁,所以可以使用传引用返回;const
修饰引用,这是一个权限的缩小,可以实现,功能是限制通过func()的返回值来修改ret。
结论:传值返回用const修饰没有意义。
2)问题2:
class Date
{
public:
//成员函数
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// 这两个函数构成重载吗?
void print() const
{
cout << _year << "/" << _month << "/" << _day << endl;
}
void print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
//成员变量
int _year;
int _month;
int _day;
};
构成重载,在自定义参数被const修饰的情况下,默认调用void print() const
,在自定义参数不被限制的情况下,默认调用void print()
。
上面的程序只是一个比较好的例子,没有实际意义,看一个有意义的场景:
// 容量是10的静态顺序表
class SeqList
{
public:
// 成员函数
void Push(int x)
{
_a[_size++] = x;
}
// 重载[]
int& operator[](size_t i)
{
assert(i < _size);
return _a[i];
}
int size()
{
return _size;
}
private:
// 成员变量
int* _a = (int*)malloc(sizeof(int) * 10); // 这样的写法后面再详细介绍
size_t _size = 0;
size_t _capacity = 10;
};
int main()
{
SeqList s;
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
for (size_t i = 0; i < 4; i++)
{
// cout << s.operator[](i) << " ";
cout << s[i] << " ";
}
cout << endl;
for (size_t i = 0; i < 4; i++)
{
s[i]++;
}
for (size_t i = 0; i < 4; i++)
{
cout << s.operator[](i) << " ";
}
cout << endl;
return 0;
}
输出结果:
1 2 3 4
2 3 4 5
我们觉得输出这个功能使用的太频繁了,可以用一个函数来封装:
void print(const SeqList& sl) // 用const修饰,因为不希望在print中修改顺序表
{
for (size_t i = 0; i < sl.size(); i++) // 编不过
{
cout << sl[i] << " "; // 编不过
}
cout << endl;
}
发现size()
函数编不过,重载的[]
也编不过,因为sl有const
修饰。这很好解决,我们只需要用const
修饰size()
函数和[]
重载函数的指针即可:
// 函数在类中定义
// 重载[]
int& operator[](size_t i) const
{
assert(i < _size);
return _a[i];
}
int size() const
{
return _size;
}
当我们以为这就万事大吉时,新的问题又接踵而至:
void print(const SeqList& sl)
{
for (size_t i = 0; i < sl.size(); i++)
{
sl[i]++; // 竟然编过了
cout << sl[i] << " ";
}
cout << endl;
}
sl明明有const
修饰,为什么还能修改呢?
因为
const
本质上修饰的是成员变量,被const
修饰的是sl,_a是不可以改的,但是_a所指向的内容是可以改的。所以这个[]
重载函数实际上是有问题的。
在[]
重载函数前加上const
修饰会怎么样?
const int& operator[](size_t i) const
{
assert(i < _size);
return _a[i];
}
又出了问题,主函数中的s[i]++
实现不了了。这时,我们可以写两个[]
重载函数,让他们俩构成重载,编译器会自己选择合适的[]
重载函数来使用:
// 容量是10的静态顺序表
class SeqList
{
public:
// 成员函数
void Push(int x)
{
_a[_size++] = x;
}
// 重载[]
// 函数1 只读
const int& operator[](size_t i) const
{
assert(i < _size);
return _a[i];
}
// 函数2 读写
int& operator[](size_t i)
{
assert(i < _size);
return _a[i];
}
int size() const
{
return _size;
}
private:
// 成员变量
int* _a = (int*)malloc(sizeof(int) * 10); // 这样的写法后面再详细介绍
size_t _size = 0;
size_t _capacity = 10;
};
void print(const SeqList& sl)
{
for (size_t i = 0; i < sl.size(); i++)
{
sl[i]++; // 编译器调用函数1,编不过了
cout << sl[i] << " ";
}
cout << endl;
}
int main()
{
Date d1(2023, 8, 7);
SeqList s;
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
for (size_t i = 0; i < 4; i++)
{
// cout << s.operator[](i) << " ";
cout << s[i] << " ";
}
cout << endl;
for (size_t i = 0; i < 4; i++)
{
s[i]++; // 编译器调用函数2,可以编过
}
for (size_t i = 0; i < 4; i++)
{
cout << s.operator[](i) << " ";
}
cout << endl;
print(s);
return 0;
}
4.总结:
只读函数可以加const(建议都加),内部不涉及修改成员变量的就是只读函数。
3.8取地址及const取地址重载
1.理解取地址重载:
class Date
{
public:
Date* operator&()
{
return this;
}
const Date* operator&() const
{
return this;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
这两个运算符一般不需要自己去写,用编译器默认生成的取地址重载即可。
2.使用场景(一种特殊情况):
想让别人通过取地址获得指定内容。例:
class Date
{
public:
// 特殊需求:
// 普通对象不能被取到地址,const对象可以
Date* operator&()
{
return nullptr;
}
const Date* operator&() const
{
return this;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
实践中这种特殊需求非常少。
3.9重载<<和>>
1.先再理解一下<<
和>>
:(了解即可)
cout << 1
这段代码,本质上是调用了一个ostream
类的成员函数:ostream& operator<< (int val)
,cout
(左操作数)是ostream
类型的对象,右操作数可以是任意内置类型数据,不同的右操作数构成重载,支持各种类型的参数输出:
对于输入,cin
是istream
类型的对象,右操作数可以是任意内置类型数据。
2.引入:(重载<<
)
如何以流插入流输出的方式访问自定义类型成员?下面这种方式可行吗?
int main()
{
Date d1(2023, 7, 8);
cout << d1; // 报错
return 0;
}
这种方式显然是不可行的,<<
只针对内置类型的数据,需要重载<<
。但是,重载函数不适合定义在类的成员函数中:
class Date
{
public:
//成员函数
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void operator<<(ostream& out)
{
out << _year << "/" << _month << "/" << _day << endl;
}
//成员变量
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2023, 7, 8);
cout << d1; // 报错
d1 << cout; // 编过了,但是不符合使用习惯
return 0;
}
分析:因为<<
的左操作数是ostream
类型的对象,而我们定义的类的成员函数中,第一个参数默认就是this
指针,只能把ostream
类型的数据放在第二个参数的位置,这就导致cout << d1
参数顺序反了,编不过;而d1 << cout
参数顺序是正确的,编过了。但是d1 << cout
这样的写法显然是不符合使用习惯的,所以这样写也不好。
解决方法:只能写在全局。
// 全局函数
void operator<<(ostream& out, const Date& d)
{
out << d._year << "/" << d._month << "/" << d._day << endl;
}
但是成员变量是私有的,无法直接访问,我们在类中加一个友元声明friend void operator<<(ostream& out, const Date& d);
,就可以让这个函数访问成员变量了(友元声明写在哪个位置都可以,可以写在public
里,也可以写在private
里,不影响)。
class Date
{
// 友元声明
friend void operator<<(ostream& out, const Date& d);
public:
// 成员函数
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// 成员变量
private:
int _year;
int _month;
int _day;
};
void operator<<(ostream& out, const Date& d)
{
out << d._year << "/" << d._month << "/" << d._day << endl;
}
int main()
{
Date d1(2023, 7, 8);
cout << d1;
return 0;
}
又出现一个新问题:我们希望重载过的<<
能像默认的<<
一样连续打印数据。但是连续打印会报错:
int main()
{
Date d1(2023, 7, 8);
Date d2;
cout << d1 << d2; // 报错
return 0;
}
这是因为重载函数的返回值出了问题,我们只需要模仿默认的<<
写法,让其返回ostream&
即可:
class Date
{
// 友元声明
friend ostream& operator<<(ostream& out, const Date& d);
public:
// 成员函数
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// 成员变量
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& out, const Date& d)
{
out << d._year << "/" << d._month << "/" << d._day << endl;
return out;
}
int main()
{
Date d1(2023, 7, 8);
Date d2;
cout << d1 << d2 << endl;
return 0;
}
3.重载>>:
cin >> a
,对于这段代码,cin
是istream
类型的变量,a
是任意内置类型变量。重载>>
的函数可以参考重载<<
的写法:
1)要写成全局函数。
2)要有友元声明。
3)返回值是istream&
类型的。
4)不加const
修饰自定义类型变量。
class Date
{
// 友元声明
friend istream& operator>>(istream& in, Date& d);
public:
//成员函数
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
//成员变量
private:
int _year;
int _month;
int _day;
};
istream& operator>>(istream& in, Date& d) // 不加const
{
in >> d._year >> d._month >> d._day;
return in;
}
int main()
{
Date d2;
cin >> d2;
cout << d2;
return 0;
}