[英]How to define operator overloading for 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 =
。 謝謝!
編輯: void gain_priority_array(const std :: vector&weighting, const std::vector<int> &sample=NULL
)失敗!
引用不能為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
}
}
您的誤解始於建議添加operator=
以允許使用該類型的默認參數。 在您的示例中,不是調用operator=
,而是ABC(int)
。
使用std::vector
時不接受您的代碼的原因是NULL
轉換為0(至少幾乎在您看到的所有時間它都執行),並且是唯一可以占用std::vector
構造函數0,表示計數多少個項目,被標記為顯式。
為了解決當前的問題,可以將語法更改為:
const std::vector<int> &priority_array = std::vector<int>(0)
但是,這引入了不同的語義。 通過使用NULL
,您似乎希望它不代表任何向量。 如果未提供,則此版本將提供一個空載體。 它根本不是矢量。 如果您希望區分,則應使用boost的可選庫或簡單的指針,因為引用不是正確的工具。
當使用=
創建引用時,根本就沒有調用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
當然,僅使用指針而不是引用會更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.