2012-09-06 52 views
2

在C#,重載操作者諸如「+」,「 - 」等,我必須使函數的類的一個靜態成員:我可以在課堂中重載靜態操作符嗎?

class MyType 
{ 
    /*...*/ 

    public static MyType operator+ (MyType a, MyType b) 
    { 
     MyType ret; 
     /* do something*/ 
     return ret; 
    } 
} 

據我所知,在C++中,這是我怎樣可以重載操作:

class MyType 
{ 
    /*...*/ 

public: 
    MyType operator+ (MyType b) // *this is the first operand 
    { 
     MyType ret; 
     /* do something*/ 
     return ret; 
    } 
}; 

的問題是,*this是第一操作數的,所以第一個操作數的類型必須是的MyType的。例如,如果我要添加MyType爲整數:

MyType a, b; 
b = a + 1; // Valid 
b = 1 + a; // Error 

在C#,我可以重載「+」運算符對於每種情況。

我的問題是:我可以在C++中使用與C#中相同的方法,使用靜態運算符嗎?據我所知,有一種方法可以與朋友操作員做到這一點,但在繼承該功能時會丟失。

+1

'朋友'是你的朋友。 – Mehrdad

+0

你是什麼意思「他們迷路了」? –

+0

@MooingDuck我的意思是繼承的功能失去了基礎的朋友。 – Tibi

回答

3

請在左側的超載operator+int自由函數,而不是的MyType成員函數:

class MyType 
{ 
    ... 

    // MyType + int can be a member function because MyType 
    // is the type of the sum's left hand side 
    MyType operator+(int rhs) const; 
}; 

// int + MyType needs to be a free function because 
// int is the type of the sum's left hand side 
MyType operator+(int lhs, const MyType &rhs); 

另一種常見的成語是使重載類的感興趣的friend。現在,您可以實現相同的方式兩種情況:

class MyType 
{ 
    ... 

    friend MyType operator+(int lhs, const MyType &rhs) 
    { 
    // get access to MyType's private members here 
    // to implement the sum operation 
    ... 
    } 

    friend MyType operator+(const MyType &lhs, int rhs) 
    { 
    // you can also implement the symmetric case 
    // of int on the right hand side here 
    ... 
    } 
}; 

注意的是,即使operator+重載樣子成員函數在第二個例子中,他們是由於其宣佈爲真正的自由函數生活在全球範圍內friend s的MyType

3

您可以在C++的全局範圍內定義一個運算符,例如

MyType operator+ (const MyType& a, const MyType& b) 
{ 
    MyType ret; 
     /* do something*/ 
    return ret; 
} 

您可能需要的朋友聲明添加到MyType如果操作者應訪問類的私有成員。

+0

也許帶他們通過const參考... – Mehrdad

+1

@Mehrdad:剛糾正錯字。 – Andrey

相關問題