一元操作符重载

 操作符重载就是把操作符(比如'+,-,*,/'这些运算符)赋于新的意义。

 C++有许多内置的数据类型,包括int,char,double等,每一种类型都有许多运算符,例如加,减,乘,除等。当用户定义了类的对象时,两个对象之间是不能进行这些操作的,比如定义一个Money类的对象,它有元和角两个变量,对象a的属性是5元5角,对象b的属性是3元7角,总共是9元2角。但是a+b,这样的语句如果没有重载+运算符就会出错。你需要重新定义+的功能,使其按照你定义的规则进行处理。可以先把a对象的5元5角化成55角,b化成37角,然后以角为单位相加。加完之后再化成元角的形式返回给对象。

 

#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;

//Class for amounts of money in U.S. currency.
class Money
{
public:
	Money( );
	Money(double amount);
	Money(int dollars, int cents);
	Money(int dollars);
	double getAmount( ) const;
	int getDollars( ) const;
	int getCents( ) const;
	void input( ); //Reads the dollar sign as well as the amount number.
	void output( ) const;
	const Money operator +(const Money& amount2) const;
	const Money operator -(const Money& amount2) const;
	bool operator ==(const Money& amount2) const;
	const Money operator -( ) const;
private:
	int dollars; //A negative amount is represented as negative dollars and
	int cents; //negative cents. Negative $4.50 is represented as -4 and -50

	int dollarsPart(double amount) const;
	int centsPart(double amount) const;
	int round(double number) const;
};

int main( )
{
	Money yourAmount, myAmount(10, 9);
	cout << "Enter an amount of money: ";
	yourAmount.input( );

	cout << "Your amount is "; 
	yourAmount.output( ); 
	cout << endl;
	cout << "My amount is "; 
	myAmount.output( ); 
	cout << endl;

	if (yourAmount == myAmount)
		cout << "We have the same amounts.\n";
	else
		cout << "One of us is richer.\n";

	Money ourAmount = yourAmount + myAmount;
	yourAmount.output( ); cout << " + "; myAmount.output( ); 
	cout << " equals "; ourAmount.output( ); cout << endl;

	Money diffAmount = yourAmount - myAmount;
	yourAmount.output( ); cout << " - "; myAmount.output( ); 
	cout << " equals "; diffAmount.output( ); cout << endl;

	return 0;
}

/* 第一个const表示Money为常量类型,第二个const表示不改变调用实参,第二个const表示不改变调用对象*/
const Money Money::operator +(const Money& secondOperand) const
{
	int allCents1 = cents + dollars*100;
	int allCents2 = secondOperand.cents + secondOperand.dollars*100;
	int sumAllCents = allCents1 + allCents2;
	int absAllCents = abs(sumAllCents); //Money can be negative.
	int finalDollars = absAllCents/100;
	int finalCents = absAllCents%100;

	if (sumAllCents < 0)
	{
		finalDollars = -finalDollars;
		finalCents = -finalCents;
	}

	return Money(finalDollars, finalCents);
}

const Money Money::operator -(const Money& secondOperand) const
{
	int allCents1 = cents + dollars*100;
	int allCents2 = secondOperand.cents 
		+ secondOperand.dollars*100;
	int diffAllCents = allCents1 - allCents2;
	int absAllCents = abs(diffAllCents); 
	int finalDollars = absAllCents/100;
	int finalCents = absAllCents%100;

	if (diffAllCents < 0)
	{
		finalDollars = -finalDollars;
		finalCents = -finalCents;
	}

	return Money(finalDollars, finalCents);
}
bool Money::operator ==(const Money& secondOperand) const
{
	return ((dollars == secondOperand.dollars)
		&& (cents == secondOperand.cents));
}

const Money Money::operator -( ) const
{
	return Money(-dollars, -cents);
}

Money::Money( ): dollars(0), cents(0)
{/*Body intentionally empty.*/}

Money::Money(double amount)
	: dollars(dollarsPart(amount)), cents(centsPart(amount))
{/*Body intentionally empty*/}

Money::Money(int theDollars)
	: dollars(theDollars), cents(0)
{/*Body intentionally empty*/}

//Uses cstdlib:
Money::Money(int theDollars, int theCents)
{
	if ((theDollars < 0 && theCents > 0) || (theDollars > 0 && theCents < 0))
	{
		cout << "Inconsistent money data.\n";
		exit(1);
	}
	dollars = theDollars;
	cents = theCents;
}

double Money::getAmount( ) const
{
	return (dollars + cents*0.01);
}

int Money::getDollars( ) const
{
	return dollars;
}

int Money::getCents( ) const
{
	return cents;
}

//Uses iostream and cstdlib:
void Money::output( ) const
{
	int absDollars = abs(dollars);
	int absCents = abs(cents);
	if (dollars < 0 || cents < 0)//accounts for dollars == 0 or cents == 0
		cout << "$-";
	else
		cout << '$';
	cout << absDollars;

	if (absCents >= 10)
		cout << '.' << absCents;
	else
		cout << '.' << '0' << absCents;
}

//Uses iostream and cstdlib:
void Money::input( )
{
	char dollarSign;    //先输入美元符号'$'
	cin >> dollarSign; //hopefully
	if (dollarSign != '$')
	{
		cout << "No dollar sign in Money input.\n";
		exit(1);
	}

	double amountAsDouble;   //再输入钱数
	cin >> amountAsDouble;
	dollars = dollarsPart(amountAsDouble);   //分别取得美元和美分部分
	cents = centsPart(amountAsDouble);
}

int Money::dollarsPart(double amount) const
{
	return static_cast<int>(amount);   //向下取整 <int>(2.9)为2 截断取整
}

int Money::centsPart(double amount) const
{
	double doubleCents = amount*100;
	int intCents = (round(fabs(doubleCents)))%100;//   负数用%会出错   can misbehave on negatives 取余数
	if (amount < 0)
		intCents = -intCents;
	return intCents;
}

int Money::round(double number) const        //四舍五入取整,const不改变调用对象number,
{
	return static_cast<int>(floor(number + 0.5));
}







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的重载操作符指的是通过定义类的特殊方法,使得该类的对象可以支持相应的操作符。以下是一些常用的重载操作符及其对应的特殊方法: - 加法操作符: `+`,特殊方法名为 `__add__(self, other)`。 - 减法操作符: `-`,特殊方法名为 `__sub__(self, other)`。 - 乘法操作符: `*`,特殊方法名为 `__mul__(self, other)`。 - 除法操作符: `/`,特殊方法名为 `__truediv__(self, other)`。 - 取模操作符: `%`,特殊方法名为 `__mod__(self, other)`。 - 按位与操作符: `&`,特殊方法名为 `__and__(self, other)`。 - 按位或操作符: `|`,特殊方法名为 `__or__(self, other)`。 - 按位异或操作符: `^`,特殊方法名为 `__xor__(self, other)`。 - 左移操作符: `<<`,特殊方法名为 `__lshift__(self, other)`。 - 右移操作符: `>>`,特殊方法名为 `__rshift__(self, other)`。 - 一元操作符: `+`,特殊方法名为 `__pos__(self)`。 - 一元操作符: `-`,特殊方法名为 `__neg__(self)`。 - 一元取反操作符: `~`,特殊方法名为 `__invert__(self)`。 - 小于操作符: `<`,特殊方法名为 `__lt__(self, other)`。 - 小于等于操作符: `<=`,特殊方法名为 `__le__(self, other)`。 - 等于操作符: `==`,特殊方法名为 `__eq__(self, other)`。 - 大于等于操作符: `>=`,特殊方法名为 `__ge__(self, other)`。 - 大于操作符: `>`,特殊方法名为 `__gt__(self, other)`。 通过定义这些特殊方法,我们可以自定义类的行为,使其支持与内置类型相同的操作符

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值