CD18.【C++ Dev】类和对象(9)(声明和定义分离的写法以及代码复用)
目录
1.可以将声明写在类里面,将定义写在类外面
Date.h写入声明
Date.cpp写入成员函数的定义,再包含Date.h
检查是否能正常调用成员函数
2.论代码的复用
方法1:修改operator<
方法2:复用operator<和operator==
operator!=
operator<=
operator>
写法1.<=的反面
写法2.既不<也不==
operator>=
写法1.<的反面
写法2.>或==
承接CD17.【C++ Dev】类和对象(8):赋值运算符重载文章
1.可以将声明写在类里面,将定义写在类外面
还是以日期类为例:
Date.h写入声明
#pragma once
#include <iostream>
using namespace std;
class Date
{
public:
Date(int year = 0, int month = 0, int day = 0);
Date(const Date& x);
void Print();
bool operator< (const Date& d2);
int _year;
int _month;
int _day;
};
注意:缺省参数写在声明中
Date.cpp写入成员函数的定义,再包含Date.h
#include "Date.h"
Date::Date(int year , int month, int day)//指定类域
{
_year = year;
_month = month;
_day = day;
}
Date::Date(const Date& x)//指定类域
{
cout << "Date(const Date& x)" << endl;
_year = x._year;
_month = x._month;
_day = x._day;
}
void Date::Print()//指定类域
{
cout << _year << "/" << _month << "/" << _day << endl;
}
bool Date::operator< (const Date& d2)//指定类域
{
if (_year < d2._year)
return true;
else if (_year == d2._year && _month < d2._month)
return true;
else if (_year == d2._year && _month == d2._month && _day < d2._day)
return true;
return false;
}
注:当声明和定义分离时,定义需要写类域,否则编译器无法区分是普通函数还是成员函数
检查是否能正常调用成员函数
main.c写入:
#include "Date.h"
int main()
{
Date d1(2025, 3, 18);
Date d2(2025, 3,24);
d1.Print();
cout << (d1 < d2) << endl;
return 0;
}
运行结果:结果是正确的
2.论代码的复用
前面代码给出了operator<的定义,问operator>怎么写?
方法1:修改operator<
将operator<定义里面的<全部改成>,得到operator>:
bool Date::operator> (const Date& d2)
{
if (_year > d2._year)
return true;
else if (_year == d2._year && _month > d2._month)
return true;
else if (_year == d2._year && _month == d2._month && _day > d2._day)
return true;
return false;
}
这样写没有什么问题,但缺点是代码过于冗长,可以复用operator<
方法2:复用operator<和operator==
先补一个operator==的代码:
bool Date::operator== (const Date& d2)
{
return ((_year == d2._year) && (_month == d2._month) && (_day == d2._day));
}
复用的含义和修改不同,之后只需要复用operator<和operator==就可以简洁写出operator<=,operator>=,operator!=,operator>代码
operator!=
即对operator==的结果取反,需要显式使用*thi来比较*this对象和d2对象,如下:
bool Date::operator!=(const Date& d2)
{
return !(*this == d2);
}
operator<=
即operator==和operator<任何一个为真,则operator<=返回真,如下:
bool Date::operator<=(const Date& d2)
{
return *this < d2 || *this == d2;
}
operator>
两种写法
写法1.<=的反面
bool Date::operator>(const Date& d2)
{
return !(*this <= d2);
}
复用分析:operator>复用了operator<=的代码,而operator<=复用了operator<和operator==的代码,为嵌套复用
写法2.既不<也不==
bool Date::operator>(const Date& d2)
{
return !(*this < d2) && !(*this == d2);
}
显然写法1更直截了当,可读性好,写法2有点啰嗦
operator>=
写法1.<的反面
bool Date::operator>=(const Date& d2)
{
return !(*this<d2);
}
写法2.>或==
bool Date::operator>=(const Date& d2)
{
return *this > d2 || *this == d2;
}
下篇文章将完善日期类对象的其他运算符重载