天天看點

對下标運算符[]和函數調用運算符()的重載

一.對下标運算符[]的重載:

 重載的格式:傳回類型 類名 operator [](參數);

#include<iostream>

using namespace std;

class A

{

public:

A(int n);

~A();

int & operator [](int n);//傳回類型為int & 引用類型

private:

int *p;

int size;

};

int & A::operator[](int n){

return p[n];//傳回p[n]

}

A::A(int n)

p = new int[n];

A::~A()

delete[]p;

int main(){

A a(5);

a[3] = 4;//等價于a.operator[](3)=4,相當于4指派給了p[3];

cout << "a[3]=" << a[3] << endl;

cin.get();

return 0;

二.對()運算符的重載

class A{

float operator()(double a,double b);

float A::operator ()(double a,double b){

return a*b;

A f;

float a=f(10.0,1.23);//預設double類型

cout<<a<<endl;

三.對流輸出運算符‘<<’和流輸出‘>>’的重載

int& operator[](int);//這裡用傳回值類型為引用類型,完全是效率問題。

friend ostream& operator <<(ostream &otput, A& a);//對<<的重載最好用友員函數

friend istream& operator >>(istream &input, A& b);

int& A::operator[](int a){

if (a<size&&a>=0)

return p[a];

cout << "out of size" << endl;

exit(0);

ostream& operator <<(ostream &otput, A& a){

for (int i = 0; i < a.size; i++)

otput << a.p[i]<<' ';

cout << endl;

return otput;

istream& operator >>(istream &input, A& b){

for (int i = 0; i < b.size; i++){

input >> b.p[i];

return input;//這裡傳回值為istream 類型變量是規定。

size = n;

size = 0;

cout << "input the elements of A a" << endl;

cin >> a;

//cout << "a[5]" << a[5]<<endl;//直接退出。

cout << a<<endl;

system("pause");

本文轉自 神迹難覓 51CTO部落格,原文連結:http://blog.51cto.com/ji123/1915670,如需轉載請自行聯系原作者

繼續閱讀