我有一個使用矢量<的std :: string >內部容器類。我已經提供了一個方法AddChar(std :: string)到這個包裝類,它向內部向量執行push_back()。在我的代碼中,我必須在容器中添加多個項目。爲此我必須使用
container.AddChar("First");
container.AddChar("Second");
這會使代碼變大。所以爲了使它更容易,我計劃超載運營商< <。所以我可以寫
container << "First" << "Second"
和兩個項目將被添加到底層向量。
這裏是我用於該
class ExtendedVector
{
private:
vector<string> container;
public:
friend ExtendedVector& operator<<(ExtendedVector& cont,const std::string str){
cont.AddChar(str);
return cont;
}
void AddChar(const std::string str)
{
container.push_back(str);
}
string ToString()
{
string output;
vector<string>::iterator it = container.begin();
while(it != container.end())
{
output += *it;
++it;
}
return output;
}
};
它按預期工作的代碼。
問題
- 是運算符重載正確寫入?
- 在這種情況下重載操作符是否是一種好習慣?
- 此代碼是否會有任何性能問題或任何其他問題?
有什麼想法?
編輯
聽到很好的意見後,我決定不超載< <,因爲它沒有意義在這裏。我刪除了運算符重載代碼,這裏是最終的代碼。
class ExtendedVector
{
private:
vector<string> container;
public:
ExtendedVector& AddChar(const std::string str)
{
container.push_back(str);
return *this;
}
.. other methods
}
這讓我通過使用params關鍵字添加
container.AddChar("First").AddChar("Second")
在C#中,我可以做到這一點更容易。代碼會像
void AddChar(params string[] str)
{
foreach(string s in str)
// add to the underlying collection
}
我知道在C++中,我們可以使用...指定的參數變量langth。但是AFAIK,它不是類型安全的。那麼這是一個推薦的做法嗎?所以我可以寫
container.AddChar("First","Second")
感謝您的答覆。
Qt使用operator <<爲QStringList:http://doc.trolltech.com/4.4/qstringlist.html,我喜歡它的使用。但通常我會注意不要添加太多的操作員。正如凱文所說,它可能會變得混亂如地獄:) – 2009-03-02 04:09:38