资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

对下标运算符[]和函数调用运算符()的重载

一.对下标运算符[]的重载:

吉首网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。创新互联公司自2013年创立以来到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司

 重载的格式:返回类型 类名 operator [](参数);

  

  1. #include

  2. using namespace std;

  3. class A

  4. {

  5. public:

  6. A(int n);

  7. ~A();

  8. int & operator [](int n);//返回类型为int & 引用类型

  9. private:

  10. int *p;

  11. int size;

  12. };

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

  14. return p[n];//返回p[n]

  15. }

  16. A::A(int n)

  17. {

  18. p = new int[n];

  19. }

  20. A::~A()

  21. {

  22. delete[]p;

  23. }

  24. int main(){

  25. A a(5);

  26. a[3] = 4;//等价于a.operator[](3)=4,相当于4赋值给了p[3];

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

  28. cin.get();

  29. return 0;

  30. }

二.对()运算符的重载

#include

using namespace std;

class A{

public:

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

};

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

return a*b;

}

int main(){

A f;

float a=f(10.0,1.23);//默认double类型

cout<

return 0;

}

三.对流输出运算符‘<<’和流输出‘>>’的重载

#include

using namespace std;

class A

{

public:

A(int n);

~A();

int& operator[](int);//这里用返回值类型为引用类型,完全是效率问题

friend ostream& operator <<(ostream &otput, A& a);//对<<的重载最好用友员函数

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

private:

int *p;

int size;

};

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

if (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 类型变量是规定。

}

A::A(int n)

{

p = new int[n];

size = n;

}

A::~A()

{

delete[]p;

size = 0;

}

int main(){

A a(5);

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

cin >> a;

//cout << "a[5]" << a[5]<

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

cout << a<

system("pause");

return 0;

}


分享文章:对下标运算符[]和函数调用运算符()的重载
文章位置:http://cdkjz.cn/article/jhhocp.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220