Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux编程 > » 正文

操作符重载

来源: 未知 分享至:

重写操作符的时候 const A& operator (符号)(参数){} 
如果第一个参数为常量的时候,例如CLASSA m = 1 + m; 
那么要定义友元类friend const A& operator(int i, A& m){};

一般操作符的左边的那个为调用者本人,操作符右侧的类是参数作为加入

单元运算的时候,左++ 和 右++为了区分需要用一个int型的参数加以区分。

const A& operator ++ () { // 左,且要临时多加一个A类多想作为返回值,因为左++,当前的返回值不改变。

}

const A& operator ++(int){ //右侧

}

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

class A{
public:
 explicit A(int num){
  b = num;
 }
 A(){
  b = 0;
 }
 const A& operator++(){
  b++;
  return *this;
 }
 const A& operator++(int){
  A t(b);
  ++b;
  return t;
 }
 void write(const A a){
  printf("current value: %d\n", a.b);
 }
 const A &operator =(const A &j){
  if(&j == this) return *this;
  b = j.b;
  return *this;
 }
 const A &operator =(int j){  
  b = j;
  return *this;
 }
 const A &operator +(const A &j){A t; t.b=b+j.b; return t;}
 const A &operator +=(const A &j){this->b=b+j.b; return *this;};
 friend const A &operator +(int i ,const A &j){A t; t.b=i+j.b; return t;}
private:
 int b;
};

int _tmain(int argc, _TCHAR* argv[])
{
 A a(100), b(200);
 //a = operator + (3, b); a.write(a);
 a += b;
 a = 1;
 a.write(a);


 a.write(++a);

 a.write(a++);

 a.write(a);
 system("pause");
 return 0;
}

 

_

_

_

********************************************

****** Never ever let you down. *****

********************************************

Tags:
分享至:
最新图文资讯
1 2 3 4 5 6
验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史