我想重載森林類中的+運算符,森林是樹的集合,+運算符應該將兩個森林合併爲一個。我有以下的代碼爲我的類定義:在C++中泛型類的重載+運算符
template<typename NODETYPE>
class Forest
{
public:
friend Forest& operator+<>(Forest&, Forest&);
friend ostream& operator<<<>(ostream&, const Forest&);
friend istream& operator>><>(istream&, Forest&);
Forest();
Forest(const Forest& otherForest);
~Forest();
void nodes(int&) const;
private:
ForestNode<NODETYPE> *root;
ForestNode<NODETYPE> *getNewNode(const NODETYPE &);
};
以下是我的執行操作+的:
template<typename NODETYPE>
Forest& operator+<>(Forest& f1, Forest& f2)
{
f3 = new Forest();
f3.root = *f1.*root;
f3.root.sibling = *f2.*root;
*f1.root = 0;
*f2.root = 0;
return f3;
}
我得到編譯如下錯誤:
|28|error: expected constructor, destructor, or type conversion before '&' token|
線28指到我的運營商+實施的簽名。
我想糾正我應該添加到返回類型,並提供:
template<typename NODETYPE>
Forest<NODETYPE>& operator+<>(Forest& f1, Forest& f2)
{
f3 = new Forest();
f3.root = *f1.*root;
f3.root.sibling = *f2.*root;
*f1.root = 0;
*f2.root = 0;
return f3;
}
但是,這使我有以下錯誤:
|28|error: declaration of 'operator+' as non-function| |28|error: missing template arguments before '&' token| |28|error: 'f1' was not declared in this scope| |28|error: missing template arguments before '&' token| |28|error: 'f2' was not declared in this scope|
誰能幫助我?我會非常感激。
爲什麼你動態分配,然後試圖返回一個指向'Forest'而不是參考?而且該函數不應該返回任何引用,沒有什麼可引用的:當你添加兩個東西時,通常最終會得到一個新的*值*,所以按值返回。這是*壞*另外,你正在操縱參數。 ('2 + 2'肯定不會改變'2'!)也許你想要一個'combine'成員函數。 – GManNickG 2010-10-27 10:43:39
在堆上分配新的森林並返回引用是一個非常糟糕的主意。只需創建一個本地對象並按值返回。 – 2010-10-27 10:45:22
或者使用智能指針,如果複製是昂貴的。 – 2010-10-27 10:51:06