C++面向对象操作符重载:算术操作符和关系操作符

1、算术操作符包括 :+、-、*、/、%(求余),-=,+=...
       逻辑运算符主要包括:<、>、==,&&,||
2、算术运算符和关系操作符要定义为非成员函数,这是因为上述的运算符均为双目运算符,且运算结束后返回的不是对象本身。
3、算术运算符一般返回一个值的拷贝,如果一定要返回某个值的引用,请一定返回const引用,因为引用可以当做左值,返回const引用,可以避免误操作。

const Book & operator+(const Book &lhs,const Book& rhs)
{
       lhs.price+=rhs.price;
       return lhs;
}
因为不能返回临时对象的引用,我们的操作只能是在左操作数或是右操作数中选择一个。如果返回非const引用,那么存在如下的情况:

m_Book1 + m_Book2 = m_Book3;
这可能是不小心而致的,这地方想要修改 + 操作返回的值,如果是非const引用,那么同时也对原值进行了修改,而这一点有可能很多人都不会意识到,所以如果要使用引用,一定要设为const引用。

倘若我们返回值的拷贝呢?

Book operator+(const Book &lhs,const Book& rhs)
{
       Book b_Temp;
       b_Temp.price = lhs.price+rhs.price;
       return b_Temp;
}
这样的操作便不会有问题了,即便我们想从新对返回的值进行赋值也是可以的。

4、看一个实际的例子:

#include <iostream>
#include <string>

using namespace std;

class MyString
{
private:
	int m_Lenth;
	string m_str;
public:
	MyString()
	{
		m_Lenth = 0;
		m_str = " ";
	}

	MyString(string strTemp):m_str(strTemp)
	{
		m_Lenth = strTemp.size();
	}

	MyString(const MyString &m_MyStr);
	MyString &operator = (const MyString &m_MyStr);
	friend MyString operator+(const MyString &lhs,const MyString &rhs);
	friend bool operator<(const MyString &lhs,const MyString &rhs);
	friend ostream& operator<<(ostream &out,const MyString& m_MyStr);
};

MyString::MyString(const MyString &m_MyStr)
{
	this->m_Lenth = m_MyStr.m_Lenth;
	this->m_str = m_MyStr.m_str;
}

MyString &MyString::operator = (const MyString &m_MyStr)
{
	MyString strTemp(m_MyStr);
	this->m_Lenth = m_MyStr.m_Lenth;
	this->m_str = m_MyStr.m_str;
	return *this;
}

MyString operator+(const MyString &lhs,const MyString &rhs)
{
	MyString strTemp;
	strTemp.m_str = lhs.m_str+rhs.m_str;
	strTemp.m_Lenth = lhs.m_Lenth+rhs.m_Lenth;

	return strTemp;
}

bool operator<(const MyString &lhs,const MyString &rhs)
{
	bool m_LessThan = false;
	if(lhs.m_str<rhs.m_str)
	{
		m_LessThan = true;
	}

	return m_LessThan;
}

ostream& operator<<(ostream &out,const MyString& m_MyStr)
{
	out<<m_MyStr.m_Lenth<<endl;
	out<<m_MyStr.m_str<<endl;

	return out;
}

int main()
{
	string str1 = "today";
	string str2 = "beautiful";

	MyString m_str1(str1);
	MyString m_str2(str2);

	cout<<"Display The Small One:"<<endl;
	cout<<(m_str1<m_str2?m_str1:m_str2)<<endl;

	MyString m_str3 = m_str1+m_str2;
	cout<<m_str3;

	return 0;
}

程序运行的结果如下所示:


这个例子借用了string模板中的算法,当然在实例中所遇到的情况千差万别,重要的是理解。一旦长缨在手,他日何惧苍龙。到目前为止,接触的已经是C++中高级的部分了,把这一部分知识学好,基础打牢,在处理大程序方面也会是得心应手的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值