Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4253239
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-04-19 20:59:31

实验目的:

    1. 掌握运算符重载的方法

    2. 当运算符函数是成员函数的时候

    3. 当运算符函数不是成员函数的时候


2. 当运算符函数是成员函数的时候


  1. #include <iostream>
  2. #include <cstring>

  3. using namespace std;

  4. class CVector
  5. {
  6. public:
  7.     CVector();
  8.     CVector(int x,int y);

  9.     void output();
  10.     //CVector operator+(CVector *this,CVector v); 这里省略了 CVector *this
  11.     CVector operator+(CVector v);
  12. private:
  13.     int x;
  14.     int y;
  15. };

  16. CVector::CVector()
  17. {
  18.     x=0;
  19.     y=0;
  20. }

  21. CVector::CVector(int x,int y)
  22. {
  23.     this->x = x;
  24.     this->y = y;
  25. }

  26. void CVector::output()
  27. {
  28.     cout<<this->x<<","<<this->y<<endl;
  29. }

  30. CVector CVector::operator+(CVector v)
  31. {
  32.     CVector temp;    
  33.     temp.x=this->x+v.x;
  34.     temp.y=this->y+v.y;
  35.     return temp;
  36. }
  37. int main()
  38. {
  39.     CVector v1(2,3),v2(2,3),v3;
  40.     //v3 = v1 + v2;
  41.     v3=v1+v2;
  42. // v3=operator+(v1+v2); 也可以实现
  43.     v3.output();
  44.     return 0;
  45. }

  1. ywx@yuweixian:~/yu/c++/chongzai$ ./chongzai1
  2. 4,6
  3. ywx@yuweixian:~/yu/c++/chongzai$





阅读(636) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~