【问题标题】:Why is my nest class being seen as abstract?为什么我的嵌套类被视为抽象的?
【发布时间】:2009-10-10 12:51:26
【问题描述】:

我有一个包含私有嵌套实现的抽象基类。当我尝试实例化非抽象嵌套实现时,visual c++ 给了我以下错误:

错误 C2259:'node::empty_node':无法实例化抽象类(第 32 行)

据我所知,我已经覆盖了基类的所有抽象成员

代码如下:

using namespace boost;
template<typename K, typename V>
class node {
protected:
    class empty_node : public node<K,V> {
    public:
        bool is_empty(){ return true; }
        const shared_ptr<K> key() const { throw empty_node_exception; }
        const shared_ptr<V> value() const { throw empty_node_exception; }
        const shared_ptr<node<K,V>> left() const { throw empty_node_exception; }
        const shared_ptr<node<K,V>> right() const { throw empty_node_exception; }
        const shared_ptr<node<K,V>> add(const shared_ptr<K> &key, const shared_ptr<V> &value) const {
            return shared_ptr<node<K,V>>();
        }
        const shared_ptr<node<K,V>> remove(const shared_ptr<K> &key) const { throw empty_node_exception; }
        const shared_ptr<node<K,V>> search(const shared_ptr<K> &key) const { return shared_ptr<node<K,V>>(this); }
    };
    static shared_ptr<node<K,V>> m_empty;
public:
    virtual bool is_empty() = 0;
    virtual const shared_ptr<K> key() = 0;
    virtual const shared_ptr<V> value() = 0;
    virtual const shared_ptr<node<K,V>> left() = 0;
    virtual const shared_ptr<node<K,V>> right() = 0;
    virtual const shared_ptr<node<K,V>> add(const shared_ptr<K> &key, const shared_ptr<V> &value) = 0;
    virtual const shared_ptr<node<K,V>> remove(const shared_ptr<K> &key) = 0;
    virtual const shared_ptr<node<K,V>> search(const shared_ptr<K> &key) = 0;


    static shared_ptr<node<K,V>> empty(){
        if(NULL == m_empty.get()){
            m_empty.reset(new empty_node());
        }
        return m_empty;
    }
};

【问题讨论】:

  • 请考虑更改标题。类虚拟的,问题是为什么它被视为抽象的。
  • 顺便说一句,您可以在输出窗口(查看->输出)中查看编译器认为哪些方法没有实现。错误窗口仅显示多行错误的第一行,输出窗口显示更多详细信息

标签: c++ abstract-class nested-class


【解决方案1】:

函数签名不匹配。基类“node”中的纯虚成员函数不是 const;派生类 'empty_node' 中的函数是 const。

您要么需要将基类虚函数设为 const,要么从派生类的成员函数中删除 const 限定符。

【讨论】:

    【解决方案2】:

    您的嵌套类缺少 keyvalueleftrightaddremovesearch 方法的非常量版本。

    您的 const 函数不会被覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 2020-05-11
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多