繁体   English   中英

c ++错误:期望的类型说明符

[英]c++ error: expected type-specifier

当我尝试使用该命令编译这个简单的链表测试程序时

g++ -o SLLtest SLLtester.cpp intSLList.o

我收到错误:

SLLtester.cpp: In function ‘int main()’:
SLLtester.cpp:4:27: error: expected type-specifier
SLLtester.cpp:4:27: error: cannot convert ‘int*’ to ‘intSLList*’ in initialization
SLLtester.cpp:4:27: error: expected ‘,’ or ‘;’

我错过了一些简单的东西,但我不确定是什么。 链接列表的标题和定义编译没有问题。 这三个文件都包含在内。

//intSLList.hh
#ifndef INT_LINKED_LIST
#define INT_LINKED_LIST

class intSLList {
public:
 intSLList(){head=tail=0;}
 void Print();
 void AddToHead(int);
 void AddToTail(int);
 int RemoveFromHead();
 int RemoveFromTail();

protected:
 struct Node {
  int info;
  Node *next;
  Node(int e1, Node *ptr = 0) {info = e1; next = ptr;}
 } *head, *tail, *tmp;
 int e1;
};

#endif

和定义:

//intSLList.cpp
#include "intSLList.hh"
#include <iostream>

void intSLList::AddToHead(int e1){
 head = new Node(e1,head);
 if (!tail)
  tail = head;
}

void intSLList::AddToTail(int e1){
 if (tail) {
  tail->next = new Node(e1);
  tail = tail->next;
 }
 else 
  head = tail = new Node(e1);
}

int intSLList::RemoveFromHead(){
 if (head){
  e1 = head->info;
  tmp = head;
  if (head == tail)
   head = tail = 0;
  else 
   head = head->next;
 delete tmp;
 return e1;
 }
 else
  return 0;    
}

int intSLList::RemoveFromTail(){
 if (tail){
  e1 = tail->info;
  if (head == tail){
   delete head;
   head = tail = 0;
  }
  else {
   for ( tmp = head; tmp->next != tail; tmp = tmp->next);
   delete tail;
   tail = tmp;
   tail->next = 0;
  } 
  return e1;
 }
 else return 0;
}

void intSLList::Print(){
 tmp = head;
 while( tmp != tail ){
  std::cout << tmp->info << std::endl;
  tmp = tmp->next;
 }
}

最后主要功能:

#include "intSLList.hh"

int main(){
 intSLList* mylist = new intSLList::intSLList();
 for ( int i = 0; i < 10; i++ ){   
  mylist->AddToTail(i);    
 }
 mylist->Print();
}

感谢您的帮助。

intSLList* mylist = new intSLList::intSLList();

这是错的。 当我们编写new intSLList() ,我们不是“调用构造函数” - 只是命名类型 - 因此完全命名构造函数(如intSLList::intSLList )是完全错误的。

所以:

intSLList* mylist = new intSLList();

无论如何,您不需要动态分配:

#include "intSLList.hh"

int main()
{
   intSLList mylist;

   for (int i = 0; i < 10; i++) {
      mylist.AddToTail(i);    
   }

   mylist.Print();
}

您试图将构造函数作为函数调用。 分配对象时将自动调用构造函数,因此更改为

intSLList mylist;

就是这样,根本不需要指针或动态分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM