2012-10-11 23 views
0

我有關於操作符重載一個問題,並且很容易定義一個類以及它的操作符重載函數如以下代碼舉例說明:如何爲STL(C++)定義運算符重載。

typedef std::vector<std::vector<int> > ARRAY; 


class ABC 
{ 
public: 
    ABC():a(0) 
    { 
    }; 
    int a; 
    ABC& operator = (int value) 
    { 
     a = value; 
     return *this; 
    } 
    ABC(int value) 
    { 
     a = value; 

    } 
}; 


void obtain_priority_array(const std::vector<double> &weighting, const ABC &priority_array=NULL) 
{ 

} 

int main() 
{ 
    vector<double> weighting; 
    weighting.push_back(0.8); 
    weighting.push_back(0.9); 
    weighting.push_back(0.6); 
    weighting.push_back(0.3); 
    weighting.push_back(0.5); 

    ABC test; 
    obtain_priority_array(weighting, test); 

    return 0; 
} 

在上述例子中,class ABC重新定義operator =使得函數void obtain_priority_array(const std::vector<double> &weighting, const ABC &priority_array=NULL)可以有一個默認參數const ABC &priority_array=NULL。我的問題是,如果函數中的最後一個參數來自STL,例如,const std::vector<int> &priority_array=NULL,我們如何重新定義operator =。謝謝!

編輯: 無效obtain_priority_array(常量的std ::矢量&權重,const std::vector<int> &sample=NULL失敗!

+2

爲什麼不改變你的函數來接受指針而不是引用?如果你只想傳遞NULL作爲默認參數。 –

+0

順便說一句,'operator ='不被默認參數調用。採用int的構造函數是:http:// liveworkspace。org/code/84813303faa93e2b1359fa90c21adba8 – chris

+0

引用被設計爲避免爲NULL。試圖通過NULL作爲參考似乎是一個糟糕的代碼概念。 – tomahh

回答

3

您的誤解始於將operator=添加爲允許該類型的默認參數。在你的例子中,調用的不是operator=,而是ABC(int)

使用std::vector時是NULL轉換爲0你的代碼是不被接受的原因(至少它幾乎所有的時間,你會看到它),以及std::vector唯一的構造函數,可以是0,對多少項目進行統計的人被標記爲明確的。

要解決眼前的問題,語法可改爲:

const std::vector<int> &priority_array = std::vector<int>(0) 

然而,這引起不同的語義。通過你的使用NULL,它看起來像你期待它不代表矢量。如果沒有給出,這個版本將提供一個空的向量。它會而不是根本不是矢量。如果你想要這種區別,你應該使用boost的可選庫或簡單的指針,因爲引用不是正確的工具。

1

當您使用=創建參考時,根本不會調用operator=。您正在初始化參考。

而不是使用NULL您可以創建類的靜態實例來表示空值。

static const ABC ABC_NULL; 

void obtain_priority_array(const std::vector<double> &weighting, const ABC &priority_array=ABC_NULL) 
{ 
    if (&priority_array == &ABC_NULL) // the default was used 

當然,使用指針代替引用會更容易。

+0

謝謝,我明白了。現在我面對的問題是,如果** std :: vector priority_array **是函數obtain_priority_array的參數,並且該函數需要** std :: vector priority_array **的默認構造函數,那我該怎麼辦? – feelfree

+0

@chris給了我正確的答案:const std :: vector &priority_array = std :: vector (NULL)。不管怎麼說,還是要謝謝你! – feelfree

3

參考文獻不能是NULL,您的問題與操作符重載無關。如果您希望能夠將NULL作爲默認值處理,請將參數類型參考切換爲指針

void obtain_priority_array(const std::vector<double>& weighting, 
          const ABC *priority_array = NULL) 
{ 
    if(priority_array == NULL) { 
    // blah 
    } else { 
    // more blah 
    } 
} 

另一種選擇是使用類似Boost.Optional的東西來表示可選參數。

typedef boost::optional<ABC> maybe_ABC; 
void obtain_priority_array(const std::vector<double>& weighting, 
          const maybe_ABC& priority_array = maybe_ABC()) 
{ 
    if(!priority_array) { 
    // blah 
    } else { 
    // more blah 
    } 
}