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++中高级的部分了,把这一部分知识学好,基础打牢,在处理大程序方面也会是得心应手的。