我有關於操作符重載一個問題,並且很容易定義一個類以及它的操作符重載函數如以下代碼舉例說明:如何爲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
)失敗!
爲什麼不改變你的函數來接受指針而不是引用?如果你只想傳遞NULL作爲默認參數。 –
順便說一句,'operator ='不被默認參數調用。採用int的構造函數是:http:// liveworkspace。org/code/84813303faa93e2b1359fa90c21adba8 – chris
引用被設計爲避免爲NULL。試圖通過NULL作爲參考似乎是一個糟糕的代碼概念。 – tomahh