C 编译器错误

C++ Compiler errors

本文关键字:错误 编译器      更新时间:2023-10-16

我正在编写C 堆栈和队列实现程序,我完成了堆栈部分,但是当编译时,我会得到这些错误

arrayListImp.cpp:18:19: error: expected unqualified-id
                arrayList[++top]= x;
                                ^
arrayListImp.cpp:28:13: error: 'arrayList' does not refer to a value
                itemPoped=arrayList[top];
                          ^
./arrayList.h:3:7: note: declared here
class arrayList{
      ^
arrayListImp.cpp:35:9: error: 'arrayList' does not refer to a value
        return arrayList[top];
               ^
./arrayList.h:3:7: note: declared here
class arrayList{
      ^
arrayListImp.cpp:46:9: error: 'arrayList' does not refer to a value
                cout<<arrayList[i]<<endl;
                      ^
./arrayList.h:3:7: note: declared here
class arrayList{
      ^
4 errors generated.

这是标题文件

#ifndef ARRAYLIST_H
class arrayList{
public:
    arrayList();
    static const int maxSize = 10;
    int array[10];
};
class stack : public arrayList{
public:
    stack();    
    void push(int x);
    void pop();
    int Top();
    int isEmpty();
    void print();
    int x;
    int top;
    int itemPoped;
    int i;
};
#define ARRAYLIST_H
#endif

arraylistimp.cpp

#include <iostream>
#include "arrayList.h"
using namespace std;
//Stack implementation
stack::stack(){
    top = -1;
}
void stack::push(int x){
    if (top == maxSize -1){
        cout<<"Stack overflow"<<endl;
    }
    else{
        arrayList[++top]= x;
        cout<<x<<", is pushed on to the stack"<<endl;
    }
}
void stack::pop(){
    if (top == -1){
        cout<<"Stack underflow"<<endl;
    }
    else{
        itemPoped=arrayList[top];
        top--;
        cout<<itemPoped<<", is poped from the stack"<<endl; 
    }
}
int stack::Top(){
    return arrayList[top];
}
int stack::isEmpty(){
    if (top == -1) return 1;
    return 0;
}
void stack::print(){
    cout<<"Stack: "<<endl;
    for (i = 0; i<=top; i++){
        cout<<arrayList[i]<<endl;
    }
}

arraylistuse.cpp

#include <iostream>
#include "arrayList.h"
using namespace std;

int main()
{
    //Stack testing
    stack S;
    S.push(1);S.print();
    S.push(2);S.print();
    S.push(3);S.print();
    S.pop();S.print();
    S.push(4);S.print();
    //Queue testing

    return 0;
}

您能指出我在这里做错了什么吗?

您应该只读取错误消息。

  1. 您应该使用array代替arrayList,这是类的名称。因此,只需参考变量即可。

    您收到的错误消息类似于

    test.cpp: In member function ‘void stack::push(int)’:
    test.cpp:44:18: error: expected unqualified-id before ‘[’ token
             arrayList[++top]= x;
                      ^
    

    检查行时,您立即看到那里有什么问题。

  2. 您声明了构造函数arrayList::arrayList(),但您没有定义它。您可以删除声明,或者应该在CPP文件中实现。

    arrayList::arrayList() {
        // do some initialization
    }
    

    您收到的错误消息类似于

    /tmp/cc4y06YN.o:test.cpp:function stack::stack(): error: undefined reference to 'arrayList::arrayList()'
    

    代码可以编译,但没有链接。因此,所有声明都可能是正确的,但是缺少一个符号。通常,当您宣布提到的内容时,情况通常是这种情况,但是您从未定义过。

您总是已经写过

arrayList[...]

您的班级名称是什么,但是阅读代码似乎想编写

array[...]

将访问数据。