操作数的重载操作符

#include <iostream>
 
class Cents
{
private:
	int m_cents;
 
public:
	Cents(int cents) { m_cents = cents; }
 
	// add Cents + Cents using a friend function
	friend Cents operator+(const Cents &c1, const Cents &c2);
 
	// subtract Cents - Cents using a friend function
	friend Cents operator-(const Cents &c1, const Cents &c2);
 
	int getCents() const { return m_cents; }
};
 
// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2)
{
	// use the Cents constructor and operator+(int, int)
	// we can access m_cents directly because this is a friend function
	return Cents(c1.m_cents + c2.m_cents);
}
 
// note: this function is not a member function!
Cents operator-(const Cents &c1, const Cents &c2)
{
	// use the Cents constructor and operator-(int, int)
	// we can access m_cents directly because this is a friend function
	return Cents(c1.m_cents - c2.m_cents);
}
 
int main()
{
	Cents cents1(6);
	Cents cents2(2);
	Cents centsSum = cents1 - cents2;
	std::cout << "I have " << centsSum.getCents() << " cents." << std::endl;
 
	return 0;
}

我们一般不推荐这个,因为不平凡的成员函数的定义是更好的保存在一个单独的.cpp文件,在类定义之外。然而,我们将在未来的教程中使用这种模式,以保持例子简洁。
不同类型的操作数的重载操作符
通常情况下,你希望你的重载操作符与不同类型的操作数一起工作。例如,如果我们有美分(4),我们可能要添加整数6到这个产生的结果美分(10)。
当C++表达式求值x + y,x和y是第一个参数,成为第二参数。当X和Y有相同的类型,它并不重要,如果你添加X + Y或Y + X -无论哪种方式,相同的版本的运营商+被称为。然而,当操作数有不同的类型时,X + Y是不相同的Y + x。

例如,仙(4)+ 6会调用操作符+(美分,int),和6美分(4)会调用操作符+(int,美分)。因此,当我们重载了不同类型的操作数的二进制操作符时,我们实际上需要写两个函数--一个用于每个情况。这里是一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
 
class Cents
{
private:
	int m_cents;
 
public:
	Cents(int cents) { m_cents = cents; }
 
	// add Cents + int using a friend function
	friend Cents operator+(const Cents &c1, int value);
 
	// add int + Cents using a friend function
	friend Cents operator+(int value, const Cents &c1);
 
 
	int GetCents() { return m_cents; }
};
 
// note: this function is not a member function!
Cents operator+(const Cents &c1, int value)
{
	// use the Cents constructor and operator+(int, int)
	// we can access m_cents directly because this is a friend function
	return Cents(c1.m_cents + value);
}
 
// note: this function is not a member function!
Cents operator+(int value, const Cents &c1)
{
	// use the Cents constructor and operator+(int, int)
	// we can access m_cents directly because this is a friend function
	return Cents(c1.m_cents + value);
}
 
int main()
{
	Cents c1 = Cents(4) + 6;
	Cents c2 = 6 + Cents(4);
 
	std::cout << "I have " << c1.getCents() << " cents." << std::endl;
	std::cout << "I have " << c2.getCents() << " cents." << std::endl;
 
	return 0;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值