【问题标题】:Multiple constructors in a C++ LinkedList class: non-class type "ClassName"C++ LinkedList 类中的多个构造函数:非类类型“ClassName”
【发布时间】:2021-10-22 00:46:05
【问题描述】:

我有一个 LinkedList 构造函数,我可以在其中传入一个数组并构建它。然后我可以通过传入整数来添加额外的节点。

但是,我还想要构造LinkedList 的选项,不带任何参数。在我的LinkedList.h 文件中,我尝试创建一个构造函数来设置firstlast 指针。我的add 方法应该构造一个Node

但是在我的main() 函数中,当我尝试使用这个构造函数时,我得到一个错误:

请求‘l’中的成员‘add’,它是非类类型‘LinkedList()’

main.cpp 中调用的其他方法也出现同样的错误。

我在构造两个构造函数时哪里出错了?

ma​​in.cpp

#include <iostream>
#include <string>

#include "LinkedList.h"

using namespace std;

int main()
{
   //int A[] {1, 2, 3, 4, 5};
   //LinkedList l(A, 5);

   LinkedList l();

   l.add(8);
   l.add(3);

   cout << l.getCurrentSize()<<endl;
   l.display();

   return 0;
}

LinkedList.h

#ifndef LINKED_LIST_
#define LINKED_LIST_

#include "IList.h"

class LinkedList: public IList
{
   protected:
      struct Node
      {
         int data;
         struct Node *next;
      };

      struct Node *first, *last;

   public:
   //constructor
   LinkedList(){first=nullptr; last=nullptr;}
   LinkedList(int A[], int n);
   
   //destructor
   virtual ~LinkedList();

   //accessors
   void display();

   virtual int getCurrentSize() const;


   virtual bool add(int newEntry);

};
#endif

LinkedList.cpp

#include <iostream>
#include <string>

#include "LinkedList.h"

using namespace std;

//constructor
LinkedList::LinkedList(int A[], int n)
{
   Node *t;
   int i = 0;

   first = new Node;
   first -> data = A[0];
   first -> next = nullptr;
   last = first;

   for(i = 1; i < n; i++) {
      t = new Node;
      t -> data = A[i];
      t -> next = nullptr;
      last -> next = t;
      last = t;
   }
};

//destructor
LinkedList::~LinkedList()
{
   Node *p = first;
   while (first) {
      first = first -> next;
      delete p;
      p = first;
   }
}

void LinkedList::display()
{
   Node *p = first;

   while(p) {
      cout << p -> data << " ";
      p = p -> next;
   }
   cout <<endl;
}

int LinkedList::getCurrentSize() const
{
   Node *p = first;
   int len = 0;

   while(p) {
      len++;
      p = p -> next;
   }
   return len;

}

bool LinkedList::add(int newEntry) 
{
   Node *temporary;
   temporary = new Node;
   temporary -> data = newEntry;
   temporary -> next = nullptr;
   
   if (first==nullptr) {
      first = last = temporary;
   } 
   else { 
      last -> next = temporary;
      last = temporary;
   }

   return true;
}

【问题讨论】:

    标签: c++ constructor


    【解决方案1】:

    问题与您的构造函数本身无关。

    LinkedList l(); 是一个名为l函数 的声明,它不接受任何参数,并返回一个LinkedList。这就是为什么编译器抱怨l 是一个非类类型

    要默认构造一个名为lLinkedList 类型的变量,请去掉括号:

    LinkedList l;
    

    或者,在 C++11 及更高版本中,您可以改用花括号:

    LinkedList l{};
    

    【讨论】:

      猜你喜欢
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 2012-05-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 2015-07-08
      相关资源
      最近更新 更多