C++ "无法将参数声明为抽象类型

C++ "Cannot declare parameter to be of abstract type

本文关键字:抽象 抽象类 类型 声明 参数 C++      更新时间:2023-10-16

我正在尝试在能够比较两件事的C++中实现通用包装器。我已经做到了如下:

template <class T>
class GameNode {
    public:
        //constructor
        GameNode( T value )
            : myValue( value )
        { }
        //return this node's value
        T getValue() {
            return myValue;
        }
        //ABSTRACT
        //overload greater than operator for comparison of GameNodes
        virtual bool operator>( const GameNode<T> other ) = 0;
        //ABSTRACT
        //overload less than operator for comparison of GameNodes
        virtual bool operator<( const GameNode<T> other ) = 0;
    private:
        //value to hold in this node
        T myValue;
};

似乎我不能以这种方式重载"<"和">"运算符,所以我想知道我能做些什么来解决这个问题。

运算符函数通过复制接受其参数。 但是,由于纯虚函数的原因,无法构造游戏节点的新实例。 您可能希望通过引用来接受这些参数。

抽象类型之所以有用,只是因为它们是多态的,实际上它们必须多态地使用(这是虚拟和纯虚拟(又名抽象)之间的区别)。

多态性需要引用或指针。 在这种情况下,您需要引用。

按值传递尝试通过复制参数来创建新对象,但无法创建抽象类型的实例。 按引用传递使用现有实例而不是创建新实例,并避免了此问题。