【问题标题】:Templates and nested classes/structures模板和嵌套类/结构
【发布时间】:2009-11-07 19:02:25
【问题描述】:

我有一个简单的容器:

template <class nodeType> list {
    public:
        struct node {
            nodeType info;
            node* next;
        };

    //...
};

现在,有一个名为_search 的函数搜索列表并返回对匹配节点的引用。现在,当我提到函数的返回类型时,我认为它应该是list&lt;nodeType&gt;::node*。这是正确的吗?当我定义内联函数时,它完美地工作:

template <class nodeType> list {
    public:
        struct node {
            nodeType info;
            node* next;
        };

        node* _search {
            node* temp;
            // search for the node
            return temp;
        }
};

但是,如果我在类之外定义函数,

template <class nodeType> list<nodeType>::node* list<nodeType>::_search() {
    //function
}

它不起作用。编译器给出一个错误说Expected constructor before list&lt;nodeType&gt;::_search 或其他东西。错误与此类似。我目前没有可以测试的机器。

真诚感谢任何帮助。

【问题讨论】:

    标签: c++ templates data-structures containers


    【解决方案1】:

    那是因为node 是一个依赖类型。您需要将签名写成如下(请注意,为了清楚起见,我将其分成了 2 行)

    template <class nodeType> 
    typename list<nodeType>::node* list<nodeType>::_search() 
    {
        //function
    }
    

    注意typename 关键字的使用。

    【讨论】:

    【解决方案2】:

    您需要告诉编译器node 是使用关键字typename 的类型。否则它会将节点视为class list 中的static 变量。每当您在列表的实现中使用节点作为类型时,添加typename

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      相关资源
      最近更新 更多