2011-06-22 23 views
0

我正在學習C++的類,我碰到這段代碼,我想知道什麼參數被用於。參數和params用法在c + +

// 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; 
} 
+0

你不需要在你的重載參數,因爲它是一個成員函數。僅當operator +是非成員函數時才使用它。 – DumbCoder

+1

@DumbCoder什麼? –

+0

@Let_Me_Be什麼? – DumbCoder

回答

3

參數是+運算符的右操作數。

下面是代碼的清潔器版本:

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

您的聲明和定義不匹配。 +1 [在你即將編輯之前]重寫好。 –

+0

他們現在做:) Thx,我完全跳過了。 –

2

Param僅僅是一個標識符指定右邊的操作數OV重載+運算符。而不是它,你可以使用任何其他的標識符。

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

正因如此,一個其他實現的例子可能是:'CVector CVector :: operator +(CVector rhs)const {return CVector(x + rhs.x,y + rhs.y); }' – KillianDS

相關問題