资讯动态

CD18.【C++ Dev】类和对象(9) 声明和定义分离的写法以及代码复用

发布时间:2026/10/17 5:37:49 来源:尧图企业网站定制
目录1.可以将声明写在类里面,将定义写在类外面Date.h写入声明Date.cpp写入成员函数的定义,再包含Date.h检查是否能正常调用成员函数2.论代码的复用方法1:修改operator方法2:复用operator和operatoroperator!operatoroperator写法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 !(*thisd2); }写法2.或bool Date::operator(const Date d2) { return *this d2 || *this d2; }工程实践中也会用到代码复用在一个程序员的水平能差到什么程度? - 苗子的回答 - 知乎回答中给了一张图片:很明显,private void removeDir(String filePath)的内部是可以复用private void removeDir(File file)的下篇文章将完善日期类对象的其他运算符重载

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑