【发布时间】:2021-10-22 00:46:05
【问题描述】:
我有一个 LinkedList 构造函数,我可以在其中传入一个数组并构建它。然后我可以通过传入整数来添加额外的节点。
但是,我还想要构造LinkedList 的选项,不带任何参数。在我的LinkedList.h 文件中,我尝试创建一个构造函数来设置first 和last 指针。我的add 方法应该构造一个Node。
但是在我的main() 函数中,当我尝试使用这个构造函数时,我得到一个错误:
请求‘l’中的成员‘add’,它是非类类型‘LinkedList()’
main.cpp 中调用的其他方法也出现同样的错误。
我在构造两个构造函数时哪里出错了?
main.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