param和params用于c ++

时间:2011-06-22 11:12:57

标签: c++

我正在用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;
}

2 个答案:

答案 0 :(得分:3)

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

以下是代码的清洁版本:

#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;
}

答案 1 :(得分:2)

Param只是一个标识符,用于指定右侧操作数ov和重载的+运算符。而不是它你可以使用任何其他标识符。

CVector a, b;
a+b; //a is the object on which you call +, b is the param