這里介紹了:
1.++obj和obj++ 如何重載.(添天占位參數(shù))
2.基本的操作符重載過(guò)程. 返回類(lèi)型 operator 操作符 參數(shù)
3.友元函數(shù) 沒(méi)有自帶的 this 指針,在重載操作符的時(shí)候,所有的參數(shù)都必須在參數(shù)中顯示聲明.
4.重載 [] 提取操作符 << >> 流操作符.
#include <iostream>
using namespace std;
// 運(yùn)算符重載 本質(zhì)是一個(gè)函數(shù)
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;
}
//占位參數(shù)來(lái) 區(qū)別 是 obj-- 還是 --obj 這里使用一個(gè)偽參數(shù) 表示后置的 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;
}
//重載提取操作符 判斷數(shù)組越界
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;
/**
* 在第一個(gè)參數(shù)需要隱式轉(zhuǎn)換的情形下,使用友元函數(shù)重載運(yùn)算符是正確的選擇
友元函數(shù)沒(méi)有this 指針,所需操作數(shù) 都必須在參數(shù)表顯式生命,很容易實(shí)現(xiàn)類(lèi)型的隱式轉(zhuǎn)換.
*/
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;
}