运算符重载的本质是一个函数
#include <iostream>
using 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<<a<<" + "<<b<<"i "<<endl;
}
private:
};
/*
Complex myAdd(Complex &c1, Complex &c2)
{
Complex tmp(c1.a+ c2.a, c1.b + c2.b);
return tmp;
}
*/
Complex operator+(Complex &c1, Complex &c2)
{
Complex tmp(c1.a+ c2.a, c1.b + c2.b);
return tmp;
}
void main()
{
Complex c1(1, 2), c2(3, 4);
//Complex c3 = c1 + c2; //用户自己定义类型 编译器无法让变量相加
//Complex myAdd(Complex &c1, Complex &c2);
//1 普通函数
//Complex c3 = myAdd(c1, c2);
//c3.printCom();
//2 operator+ 函数名称
//Complex c3 = operator+(c1, c2);
//c3.printCom();
//3 +替换 函数名
Complex c3 = c1 + c2; //思考C++编译器怎样支持操作符重载机制的 (依据类型)
c3.printCom();
{
int a =0, b = 0, c; //基础类型C++编译器知道怎样加减
c = a +b;
}
//4 把Complex类变成私有属性
//friend Complex operator+(Complex &c1, Complex &c2);
cout<<"hello..."<<endl;
system("pause");
return ;
}
为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 !
" ; 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 !
" ; 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 :
" ;
cin >> k ;
vector A( k ) ;
cout << "Input the elements of vector A :
" ;
cin >> A ;
cout << "Output the elements of vector A :
" ;
cout << A ;
system("pause");
}