一.不能被重载的运算符
运算符 | 说明 | 不能重载的原因 |
. | 成员运算符 | 为保证成员运算符对成员访问的安全性,故不允许重载 |
.* | 成员指针运算符 | 同上 |
:: | 作用域运算符 | 因该运算符左边的运算数是一个类型名,而不是一个表达式 |
:? | 三目运算符 | 在C++中没有一个定义三目运算符的语法 |
sizeof | 求大小运算符 | 其运算数是一个类型名,而不是一个表达式 |
二.常见运算符的重载
1.赋值运算符的重载
赋值运算符即为“=”;赋值运算符的重载即为对“=”的重载。
模板为 classname &operator=(classname& 实例对象)
以class HugeInteger为例
#include <cstring>
#include <sstream>
class HugeInteger{
public:
HugeInteger& operator=(const HugeInteger &h);
private:
string str;
};
HugeInteger& HugeInteger::operator=(const HugeInteger &h)
{
this->str=h.str;
return *this;
}
2.算术运算符的重载
算术运算符包括+、++、–、- -、+=、-=、/、*等。在此只以+、-、+=为例。
模板为 classname &operator运算符(classname& 实例对象)
以class complex为例
#include<iostream>
using namespace std;
class complex{
public:
complex(double r=0,double i=0){
this->r=r;
this->i=i;
}
complex operator+(complex&);
complex operator-(complex&);
complex operator+=(complex&);
private:
double r,i;
};
complex complex::operator+(complex &c){
return complex(r+c.r,i+c.i);
}
complex complex::operator-(complex &c){
return complex(r-c.r,i-c.i);
}
complex complex::operator+=(complex &c){
r+=c.r;
i+=c.i;
return *this;//return complex(r,i)亦可
}
3.关系运算符的重载
关系运算符包括> ,< ,>= ,==,!=等;在此只以>,==为例。
模板为 friend bool &operator运算符(const classname& 实例对象1,const classname& 实例对象2)
以class String为例
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class String
{
private:
string str;
public:
String(string s){str=s;}
friend bool operator>(const String &st1, const String &st2);
friend bool operator==(const String &st, const String &st2);
};
bool operator>(const String &st1, const String &st2)
{
return (std::strcmp(st1.str, st2.str) > 0);
}
bool operator==(const String &st1, const String &st2)
{
return (std::strcmp(st1.str, st2.str) == 0);
}
4.其他较为特殊的重载
在这里给出重载<<,>>,[]的方法
模板:
(1)cout<<:friend ostream &operator<<(ostream &cout,const classname& 实例对象) / ostream &operator<<(ostream &cout)
(2)cin>>:friend istream &operator>>(istream &cin,classname& 实例对象) / istream &operator>>(istream &cin)
(3)[ ]:typename & operator[ ] (形参表)
仍旧以class String为例
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class String
{
private:
string str;
public:
String(string s){str=s;}
char & operator[](int i);
friend ostream & operator<<(ostream & cout, const String & st);
friend istream & operator>>(istream & cin, String & st);
};
char &String::operator[](int i)
{
return str[i];
}
ostream &operator<<(ostream & cout, const String &st)
{
cout << st.str;
return cout;
}
istream &operator>>(istream & cin, String &st)
{
char temp[40];
is.get(temp, 40);
if (cin)
st = temp;
while (cin && cin.get() != '\n')
continue;
return cin;
}
原文链接:https://blog.csdn.net/m0_51940505/article/details/118274408