乐之者体感开发

好知者不如乐之者,体感开发请点击:http://www.enjoythis.net/

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::



转分享不如转载好,但是这里不能转载,只好复制了!


重写操作符的时候 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;
}

我转的人家的:
http://www.cnblogs.com/25-to-life/archive/2011/10/13/2211033.htm

posted on 2011-10-15 14:56  伟征  阅读(208)  评论(0编辑  收藏  举报