类运算符重载

(1)输入、输出重载必须定义非成员函数,并在类创建时声明为友元;

(2)=、[]、->必须定义为成员,否则编译器会出错;

(3)对称Operator,算术操作符(+/-/*//),关系操作符(== ,> ,  < , !),最好定义为普通非成员函数;

(4)如果定义为成员函数,则参数少一个,否则该多少就多少。之所以少一个,是因为第一个参数被默认为this的指向;

(5)改变对象状态或与类型关系密切的,最好定义为类成员。例如:++ ,-- ,*(解引用)。

简单的示例代码:

<span style="font-size:14px;">#include <iostream>
using namespace std;

class Four{
friend Four operator+(const Four & l,const Four & r);
friend ostream& operator<<(ostream& out,const Four &f);
friend istream& operator>>(istream& in, Four &f);
public:
	Four():a(0),b(0),c(0),d(0){}//默认构造函数是必要的,初始化列表是必要的,因为const,引用参数,以及没有默认构造函数的类参数的存在
	Four(int a,int b,int c,int d){
		this->a = a;
		this->b = b;
		this->c = c;
		this->d = d;
	}
	
	/*Four operator+(const Four &r){
		//Four ret;
		this->a += r.a;
		this->b += r.b;
		this->c += r.c;
		this->d += r.d;
		return *this;
	}*/
	void print(){
		cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
	}
	
private:
	int a;int b; int c; int d;
};

Four operator+(const Four& l,const Four& r){
		Four ret(l);
		ret.a += r.a;
		ret.b += r.b;
		ret.c += r.c;
		ret.d += r.d;	
		return ret;
}

ostream& operator <<(ostream & out, const Four & f){
		out<<f.a<<" "<<f.b<<" "<<f.c<<" "<<f.d;
		return out;
}

istream& operator>>(istream& in, Four &f){
	in>>f.a>>f.b>>f.c>>f.d;
	//in>>f.b;
	//in>>f.c;
	//in>>f.d;
	return in;
}

int main() {
	// your code goes here
	Four l(1,2,3,4);
	Four r(4,3,2,1);
	
	Four sum;
	sum = l + r;
	cout<<sum<<endl;
	
	Four f;
	cin>>f;
	cout<<f<<endl;
	
	return 0;
}</span>



C++中的时间运算符重载可以通过重载的成员函数或者友元函数来实现。下面是一个示例代码,展示了如何重载时间的加法运算符(+)和流插入运算符(<<): ```cpp #include <iostream> class Time { private: int hours; int minutes; public: Time(int h = 0, int m = 0) { hours = h; minutes = m; } Time operator+(const Time& t) const { Time sum; sum.minutes = minutes + t.minutes; sum.hours = hours + t.hours + sum.minutes / 60; sum.minutes %= 60; return sum; } friend std::ostream& operator<<(std::ostream& os, const Time& t) { os << t.hours << " hours, " << t.minutes << " minutes"; return os; } }; int main() { Time t1(2, 30); Time t2(1, 45); Time t3 = t1 + t2; std::cout << "Time 1: " << t1 << std::endl; std::cout << "Time 2: " << t2 << std::endl; std::cout << "Time 1 + Time 2: " << t3 << std::endl; return 0; } ``` 在上面的代码中,我们定义了一个名为Time的时间。该具有hours和minutes两个私有成员变量,并且定义了一个构造函数和两个运算符重载函数。 在运算符重载函数中,我们重载了+运算符来实现两个时间对象的相加操作。在重载函数中,我们通过创建一个新的Time对象来保存两个时间对象的和,并确保小时与分钟的进位被正确处理。 另外,我们还通过友元函数重载了流插入运算符(<<),以便能够直接使用std::cout输出Time对象。 在主函数中,我们创建了两个Time对象t1和t2,并将它们相加得到t3。然后,我们使用std::cout输出了t1、t2和t3的值。 这只是一个示例,你可以根据实际需求重载其他的运算符,如减法运算符(-)、赋值运算符(=)等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值