在“.”之前需要“类型名”,因为“.”是一个依赖范围

need ‘typename’ before ‘..’ because ‘..’ is a dependent scope

本文关键字:一个 范围 依赖 因为 类型名 类型      更新时间:2023-10-16
尝试

编译模板类时遇到问题。

在 .h 文件中

template <typename dataType>
class Node {    
 private:
    dataType nodeData;
    Node<dataType>* nextLink;
    Node<dataType>* previousLink;
 public:    
    Node(const dataType& nodeData);
   // methods

在 .template 文件中

template <typename dataType>
Node<dataType>::dataType Node<dataType>::getData() const {
    return nodeData;
};

尝试编译时遇到的错误是:

 need ‘typename’ before ‘Node<dataType>::dataType’ because ‘Node<dataType>’ is a dependent scope
 Node<dataType>::dataType Node<dataType>::getData() const {

然后我添加类型名称,然后它给我这个错误:

error: expected nested-name-specifier before ‘dataType’
       typename dataType getData() const;
                ^
error: expected ‘;’ at end of member declaration
error: declaration of ‘int Node<dataType>::dataType’
error: shadows template parm ‘class dataType’
       template <typename dataType> 
                 ^

我做错了什么?

没有

称为dataType的成员,我假设返回类型应该只是模板dataType

template <typename dataType>
dataType Node<dataType>::getData() const {
    return nodeData;
}

在这种情况下,编译器消息具有误导性,因为它找不到正确的定义,它假定dataType引用模板参数。

template <typename DataType>
class Node {
public:
    using dataType = DataType;
private:
    dataType nodeData;
    Node<dataType>* nextLink;
    Node<dataType>* previousLink;
public:    
    Node(const dataType& nodeData);
    dataType getData() const;
};
template <typename DataType>
typename Node<DataType>::dataType Node<DataType>::getData() const {
    return nodeData;
};

像这样的typename

http://melpon.org/wandbox/permlink/Agu2s6vw6OLfbbRh

所呈现的示例代码不完整,因此必须猜测具体问题。

但是,以下是以实用方式完成该类的方法,而不会遇到像您遇到的问题:

template< class Item >
struct Node
{
    Node* next;
    Node* prev;
    Item item;
};

表明有时可以在不知道确切细节的情况下解决问题。