在C++中对泛型类重载+运算符

joe*_*ian 4 c++ templates overloading operator-keyword

我正在尝试重载林类中的+运算符,林是树的集合,而+运算符应该将两个林合并为一个.我有以下代码作为我的类定义:

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 &);
};
Run Code Online (Sandbox Code Playgroud)

以下是我对operator +的实现:

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;
}
Run Code Online (Sandbox Code Playgroud)

我在编译时遇到以下错误:

|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;
}
Run Code Online (Sandbox Code Playgroud)

但这给了我以下错误:

|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|

谁能帮我这个?我会非常感激的.

小智 6

编写operator +的关键是不要写operator +. 相反,写一个副本ctor和operator + =:

template<class NodeType>
struct Forest {
  //...
  Forest(Forest const &other);
  //...
  Forest& operator+=(Forest const &other) {
    // code here
    return *this;
  }
  //...
};
Run Code Online (Sandbox Code Playgroud)

现在我们添加operator +:

template<class NodeType>
struct Forest {
  //...
  friend Forest operator+(Forest a, Forest const &b) {
    a += b;
    return a;
  }
  //...
};
Run Code Online (Sandbox Code Playgroud)

就是这样!复制通常是直截了当的(有时候是被禁止的),用+ =比+来思考可能更简单(你有两个对象并且改变一个,而不是从两个中创建第三个对象).op +的这种模式适用于任何类似的类型,甚至适用于类似的运算符,如 - ,*和/.