我正在研究C ++中的类,遇到了这段代码片段,我想知道param是用来做什么的。

// vectors: overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int,int);
    CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
  x = a;
  y = b;
}

CVector CVector::operator+ (CVector param) {
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return (temp);
}

int main () {
  CVector a (3,1);
  CVector b (1,2);
  CVector c;
  c = a + b;
  cout << c.x << "," << c.y;
  return 0;
}

最佳答案

参数是+运算符的右操作数。

这是代码的更干净的版本:

#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector ();
    CVector (int,int);
    CVector (const CVector&);
    CVector operator + (const CVector&) const;
};

CVector::CVector() : x(0), y(0) {}
CVector::CVector(int a, int b) : x(a), y(b) {}
CVector::CVector(const CVector& v) : x(v.x), y(v.y) {}

CVector CVector::operator+ (const CVector& param) const {
  CVector temp(*this);
  temp.x += param.x;
  temp.y += param.y;
  return (temp);
}

int main () {
  CVector a (3,1);
  CVector b (1,2);
  CVector c;
  c = a + b;
  cout << c.x << "," << c.y;
  return 0;
}

08-16 08:59