运算符重载的本质是一个函数
#includeusing namespace std;class A {private: int m_a; int m_b; friend A operator+(A &a1, A &a2);//友元函数訪问私有属性。实现二元运算符重载 friend A operator++(A &a); //友元函数訪问私有属性。实现一元运算符重载(前置) /*后置为避免与前置函数定义同样,使用占位符int。告诉编译器是后置运算符重载*/ friend A operator++(A &a, int); //友元函数訪问私有属性。实现一元运算符重载(后置) friend class B; //友元类,訪问私有属性。
若B类是A类的友员类,则B类的全部成员函数都是A类的友员函数
public: A(int a){ this->m_a = a; } A(int a, int b) { m_a = a; m_b = b; } void show() { cout << m_a << endl; } }; class B { private: A *pObjA = new A(21); public: void showA() { cout << pObjA->m_a << endl; } }; A operator+(A &a1, A &a2) { A tmp(a1.m_a + a2.m_a, a1.m_b + a2.m_b); return tmp; } A operator++(A &a) { //前置++ a.m_a++; a.m_b++; return a; } A operator++(A &a, int) { //后置++ A tmp = a; a.m_a++; a.m_b++; return tmp; } int main() { A a1(1, 9); A a2(3, 4); A a3 = a1 + a2; a3.show(); ++a3; a3.show(); a3++; a3.show(); return 0; }
class Complex{public: int a; int b; friend Complex operator+(Complex &c1, Complex &c2);public: Complex(int a=0, int b=0) { this->a = a; this->b = b; }public: void printCom() { cout<<<" + "<<<"i "<
为vector类重载流插入运算符和提取运算符
class vector{ public : vector( int size =1 ) ; ~vector() ; int & operator[]( int i ) ; friend ostream & operator << ( ostream & output , vector & ) ; friend istream & operator >> ( istream & input, vector & ) ;private : int * v ; int len ;};vector::vector( int size ) { if (size <= 0 || size > 100 ) { cout << "The size of " << size << " is null !\n" ; abort() ; } v = new int[ size ] ; len = size ;}vector :: ~vector() { delete[] v ; len = 0 ; }int &vector::operator[]( int i ) { if( i >=0 && i < len ) return v[ i ] ; cout << "The subscript " << i << " is outside !\n" ; abort() ;}ostream & operator << ( ostream & output, vector & ary ){ for(int i = 0 ; i < ary.len ; i ++ ) output << ary[ i ] << " " ; output << endl ; return output ;}istream & operator >> ( istream & input, vector & ary ) { for( int i = 0 ; i < ary.len ; i ++ ) input >> ary[ i ] ; return input ;}void main(){ int k ; cout << "Input the length of vector A :\n" ; cin >> k ; vector A( k ) ; cout << "Input the elements of vector A :\n" ; cin >> A ; cout << "Output the elements of vector A :\n" ; cout << A ; system("pause");}