深入解析C++编程中的运算符重载

2020-01-06 15:03:53王振洲

 
4. 编译程序如何选用哪一个运算符函数:
运算符重载实际是一个函数,所以运算符的重载实际上是函数的重载。编译程序对运算符重载的选择,遵循着函数重载的选择原则。当遇到不很明显的运算时,编译程序将去寻找参数相匹配的运算符函数。
 
5. 重载运算符有哪些限制:
(1) 不可臆造新的运算符。必须把重载运算符限制在C++语言中已有的运算符范围内的允许重载的运算符之中。
(2) 重载运算符坚持4个“不能改变”。
·不能改变运算符操作数的个数;
·不能改变运算符原有的优先级;
·不能改变运算符原有的结合性;
·不能改变运算符原有的语法结构。
 
6. 运算符重载时必须遵循哪些原则:
运算符重载可以使程序更加简洁,使表达式更加直观,增加可读性。但是,运算符重载使用不宜过多,否则会带来一定的麻烦。
(1) 重载运算符含义必须清楚。
(2) 重载运算符不能有二义性。
运算符重载函数的两种形式
运算符重载的函数一般地采用如下两种形式:成员函数形式和友元函数形式。这两种形式都可访问类中的私有成员。

三、例子
使用全局函数重载


#include <IOSTREAM.H> 
 
class A 
{ 
public: 
  A(int i):i(i){}; 
  void print(){cout<<i<<endl;} 
  friend A operator + (A &a, A &b);//声明为友元 
  friend A operator ++(A &a, int); 
  friend A& operator ++(A &a); 
  friend A& operator +=(A &a, A &b); 
protected: 
  int i; 
private: 
}; 
 
A operator + (A &a, A &b){//重载 a + b 
  return A(a.i + b.i); 
} 
 
A operator ++(A &a, int){//重载 a++ 
  return A(a.i++); 
} 
 
A& operator ++(A &a){//重载 ++a 
  a.i++; 
  return a; 
} 
 
A& operator +=(A &a, A &b){//重载 += 
  a.i += b.i; 
  return a; 
} 
 
void main(){ 
  A a(5); 
  A b(3); 
  (a += b).print(); 
} 

 
使用成员函数重载


#include <IOSTREAM.H> 
 
class A 
{ 
public: 
  A(int i):i(i){}; 
  void print(){cout<<i<<endl;} 
  A operator + (A &b); 
  A& operator += (A &b); 
  A operator ++(int); 
  A& operator ++(); 
protected: 
  int i; 
private: 
}; 
 
A A::operator + (A &b){//重载 + 
  return A(i + b.i); 
} 
 
A& A::operator+= (A &b){ 
  i += b.i; 
  return *this; 
} 
 
A A::operator++ (int){//i++ 
  return A(i++); 
} 
 
A& A::operator ++(){//++i 
  i++; 
  return *this; 
} 
 
void main(){ 
  A a = 2; 
  A b = 3; 
  (++a).print(); 
  (b++).print(); 
} 


注:相关教程知识阅读请移步到C++教程频道。