【C++初阶】ostream&、operater<<、operator<<(ostream& _cout, const Date& d)、bool引导的结构体内嵌比较函数解析

文章详细介绍了C++中日期类(Date)如何重载比较运算符operator<()和operator>(),以及友元函数operator<<(ostream&,constDate&)的实现。这两个运算符用于比较日期的先后,而友元函数则支持将日期对象输出到标准输出流。const关键字在这里用于确保参数对象不被修改,并且在const成员函数中使用,表示函数不会修改类的任何成员。

 对C++重载、判断部分的知识进行梳理 

目录

一、bool operator>(const Date& d) const【bool引导的结构体内嵌比较函数】

1.代码整体含义

2.代码两个const的含义

二、friend ostream& operator<<(ostream& _cout, const Date& d)

1. 相关基础概念 

2. 三个引用&


问题来源于下面这个日期类

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
		: _year(year)
		, _month(month)
		, _day(day)
	{}
	bool operator<(const Date& d)const
	{
		return (_year < d._year) ||
			(_year == d._year && _month < d._month) ||
			(_year == d._year && _month == d._month && _day < d._day);
	}
	bool operator>(const Date& d)const
	{
		return (_year > d._year) ||
			(_year == d._year && _month > d._month) ||
			(_year == d._year && _month == d._month && _day > d._day);
	}
	friend ostream& operator<<(ostream& _cout, const Date& d)
	{
		_cout << d._year << "-" << d._month << "-" << d._day;
		return _cout;
	}
private:
	int _year;
	int _month;
	int _day;
};



int main()
{
    Date date;
    cout<<date<<endl;
}

C++ 中,`friend ostream & operator <<(ostream &, const Point &)` 是一个友元函数的声明,用于重载输出流运算符 `<<`。下面对其各部分含义进行详细解释: ### 1. `friend` 关键字 `friend` 关键字用于声明一个函数或类为另一个类的友元。友元函数可以访问该类的私有和保护成员。在这个声明中,`operator <<` 函数被声明为 `Point` 类的友元函数,这意味着该函数可以访问 `Point` 类的私有和保护成员,尽管它不是 `Point` 类的成员函数 [^3]。 ### 2. `ostream &` 返回类型 `ostream &` 表示该函数返回一个对 `ostream` 对象的引用。`ostream` 是 C++ 标准库中用于输出流的基类,`cout` 就是 `ostream` 的一个对象。返回引用的目的是为了支持链式输出,例如 `cout << point1 << point2;`。如果不返回引用,就无法实现这样的链式调用 [^1][^3]。 ### 3. `operator <<` `operator <<` 是 C++ 中的运算符重载。`<<` 原本是位左移运算符,但在标准库中,它被重载用于输出流操作。通过重载 `<<` 运算符,可以自定义如何将 `Point` 对象输出到输出流中 [^1][^2][^3][^4]。 ### 4. 参数 - `ostream &`:第一个参数是一个对 `ostream` 对象的引用,通常是 `cout` 或其他输出流对象。通过这个引用,函数可以将数据写入到输出流中。 - `const Point &`:第二个参数是一个对 `Point` 对象的常量引用。使用常量引用可以避免不必要的对象复制,同时保证在函数内部不会修改 `Point` 对象的状态。 ### 示例代码 ```cpp #include <iostream&gt; class Point { private: int x; int y; public: Point(int x = 0, int y = 0) : x(x), y(y) {} // 友元函数声明 friend std::ostream & operator <<(std::ostream & os, const Point & pt); }; // 友元函数定义 std::ostream & operator <<(std::ostream & os, const Point & pt) { os << "(" << pt.x << ", " << pt.y << ")"; return os; } int main() { Point p(3, 4); std::cout << p << std::endl; return 0; } ``` 在这个示例中,`operator <<` 函数被定义为 `Point` 类的友元函数,它可以访问 `Point` 类的私有成员 `x` 和 `y`。函数将 `Point` 对象的坐标以 `(x, y)` 的形式输出到输出流中,并返回输出流的引用,以便支持链式输出。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值