C# · 12月 20, 2021

C++运算符的重载

  C++运算符的重载总结

class A{public: A(int d):data(d){} A operator+(A&);//成员函数 A operator-(A&); A operator*(A&); A operator/(A&); A operator%(A&); friend A operator+(A&,A&);//友元函数 friend A operator-(A&,A&); friend A operator*(A&,A&); friend A operator/(A&,A&); friend A operator%(A&,A&);private: int data;};//成员函数的形式A A::operator+(A &a){ return A(data+a.data);}A A::operator-(A &a){ return A(data-a.data);}A A::operator*(A &a){ return A(data*a.data);}A A::operator/(A &a){ return A(data/a.data);}A A::operator%(A &a){ return A(data%a.data);}//友元函数的形式A operator+(A &a1,A &a2){ return A(a1.data+a2.data);}A operator-(A &a1,A &a2){ return A(a1.data-a2.data);}A operator*(A &a1,A &a2){ return A(a1.data*a2.data);}A operator/(A &a1,A &a2){ return A(a1.data/a2.data);}A operator%(A &a1,A &a2){ return A(a1.data%a2.data);}//然后我们就可以对类的对象进行+、-、*、/了。void main(void){ A a1(1),a2(2),a3(3); a1=a2+a3; //或者 a1=a2.operator+(a3);}

注意:在进行a2+a3的时候会出错,因为我们在上面对+定义了两种方法,去掉一种即可。

后面我就只给出成员函数形式的函数声明了,关系运算符有==,!=,,=。

bool operator == (const A& ); bool operator != (const A& );bool operator < (const A& );bool operator (const A& );bool operator >= (const A& );bool operator || (const A& );bool operator && (const A& );bool operator ! ();

A& operator + ();A& operator – ();A* operator & ();A& operator * ();

A& operator ++ ();//前置++A operator ++ (int);//后置++A& operator –();//前置–A operator — (int);//后置–

A operator | (const A& );A operator & (const A& );A operator ^ (const A& );A operator <> (int i);A operator ~ ();

A& operator += (const A& );A& operator -= (const A& ); A& operator *= (const A& );A& operator /= (const A& );A& operator %= (const A& );A& operator &= (const A& );A& operator |= (const A& );A& operator ^= (const A& );A& operator <>= (int i);void *operator new(size_t size);void *operator new(size_t size,int i);void *operator new[](size_t size);void operator delete(void*p);void operator delete(void*p,int i,int j);void operator delete [](void* p);

A& operator = (const A& );char operator [] (int i);//返回值不能作为左值const char* operator () ();T operator -> ();//类型转换符operator char* () const;operator int ();operator const char () const;operator short int () const;operator long long () const;//还有很多就不写了

friend inline ostream &operator <> (istream&,A&);//输入流

两种重载方式的比较:

注意事项: