這里介紹了:
1.++obj和obj++ 如何重載.(添天占位參數)
2.基本的操作符重載過程. 返回類型 operator 操作符 參數
3.友元函數 沒有自帶的 this 指針,在重載操作符的時候,所有的參數都必須在參數中顯示聲明.
4.重載 [] 提取操作符 << >> 流操作符.
#include <iostream>
using namespace std;
// 運算符重載 本質是一個函數
class Complex{
public:
int a;
int b;
// friend Complex operator+(Complex &c1,Complex &c2);
Complex(int a = 0,int b =0){
this->a = a;
this->b = b;
}
// Complex operator+(Complex &c1){
//
// Complex temp = Complex(this->a+c1.a,this->b+c1.b);
//
// return temp;
// }
// 前置
Complex operator--(){
this->a--;
this->b--;
return *this;
}
//占位參數來 區別 是 obj-- 還是 --obj 這里使用一個偽參數 表示后置的 obj--;
Complex operator--(int){
this->a--;
this->b--;
return *this;
}
Complex operator+(int z){
this->a = this->a + z;
return *this;
}
public:
void printCom(){
cout<<a<<"+"<<b<<endl;
}
};
Complex operator+(Complex &c1,Complex &c2){
Complex tmp(c1.a+c2.a,c1.b+c2.b);
return tmp;
}
class vector{
public:
vector(int size = 1);
int & operator[](int i);
friend ostream& operator<<(ostream& output,vector&);
friend istream& operator>>(istream& input, vector&);
~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"<<"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;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
Complex c1(1,2),c2(3,4);
Complex c3 = c1+c2;
c3.printCom();
c3--;
--c3;
/**
* 在第一個參數需要隱式轉換的情形下,使用友元函數重載運算符是正確的選擇
友元函數沒有this 指針,所需操作數 都必須在參數表顯式生命,很容易實現類型的隱式轉換.
*/
c3 = c3+4;
c3.printCom();
int k;
cout<<"Input the length of vetor A:\n";
cin>>k;
vector A(k);
cout<<"Input the elements of vetor A:\n";
cin>>A;
cout<<"Output the elements of vector A:\n";
cout<<A;
return 0;
}