【问题标题】:Why can I not declare member function in C++ [closed]为什么我不能在 C++ 中声明成员函数 [关闭]
【发布时间】:2017-09-10 14:50:33
【问题描述】:

我正在构建一个 C++ 列表程序。有一个 ADT List,它是一个纯虚拟模板类,SLL(单链表)继承自它。我已经在 sll.h 中编写了类定义,并尝试在 sll.cpp 中实现该列表。但是我不断收到以下两个错误,

1)

In file included from cpp_files/sll.cpp:1:0,
                 from main.cpp:3:
cpp_files/../includes/sll.h:3:25: error: expected class-name before ‘{’ token
 class SLL : public List {

2)

cpp_files/../includes/sll.h:12:54: error: cannot declare member function ‘List<L>::insert’ within ‘SLL’
        void List<L>::insert( L element, int position );

我的问题,发生了什么?为什么这不起作用?

SLL.cpp
#include "../includes/sll.h"
/*
 Singly Linked List Implementation
*/
SLL::SLL() {}

SLL::~SLL() {}

template <class L>
void List<L>::insert( L element, int position ) {

}
SLL.H
#include "../includes/list.h"

class SLL : public List {
    private:
    public:

       SLL();

       ~SLL();

       template <class L>
       void List<L>::insert( L element, int position );

};

列表.h

#ifndef LIST_H
#define LIST_H

/*
In this code we define the headers for our ADT List.
*/
template<class L>
class List {

private:

public: // This is where functions go

  typedef struct node {
      int data;
      node* next;
  } * node_ptr;

  virtual void insert( L element, int position ) = 0;

};


#endif // LIST_H

【问题讨论】:

  • 不是你的实际问题,但你迫切需要阅读this
  • 向我们展示您的代码(证明问题的最小独立量),而不仅仅是错误消息。
  • 检查我的编辑,我的错

标签: c++ templates inheritance


【解决方案1】:

List是模板所以需要指定模板参数

class SLL : public List // no template parameter specified!

需要类似

class SLL : public List<int> // now we have a complete type

或者你需要给SLL添加一个模板参数

template<class L>
class SLL : public List<L> // now the user of SLL tells us the complete type

您也不能将模板定义的一部分放在单独的cpp 文件中,因此如果您将SLL 设为模板类,则需要将其整个定义放在标题中。您的所有模板都一样。

【讨论】:

  • 好吧,即使解决了这个问题,它也无法与单独翻译单元中的实现一起使用。
  • 错误:模板参数“L”的声明遮蔽了模板参数模板,感谢您的帮助,但它并没有真正解决任何问题
  • @user0042 好点,我加了一条注释。
  • @JohnSmith 现在您已将整个类的 SLL 声明为 template&lt;class L&gt;,您应该将其从成员函数中删除。
猜你喜欢
  • 2014-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多