-1

第 23 行是:

List[i] = x;

当我尝试编译时:

g++ w3.cpp list.cpp line.cpp
list.cpp: In member function void List::set(int):
list.cpp:23:8: error: expected unqualified-id before [ token

这是main.cpp:

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

int main() {
    int no;
    List list;

    cout << "List Processor\n==============" << endl;
    cout << "Enter number of items : ";
    cin  >> no;

    list.set(no);
    list.display();
}

这是list.h:

#include "line.h"
#define MAX_LINES 10
using namespace std;

struct List{
    private:
        struct Line line[MAX_LINES];
    public:
        void set(int no);
        void display() const;
};

这是line.h:

#define MAX_CHARS 10
struct Line {
    private:
        int num;
        char numOfItem[MAX_CHARS + 1]; // the one is null byte
    public:
        bool set(int n, const char* str);
        void display() const;
};

这是 list.cpp

#include <iostream>
#include <cstring>
using namespace std;
#include "list.h"
//#include "line.h" - commented this line because it was giving me a struct redefinition error

void List::set(int no) {

    int line;
    char input[20];

    if (no > MAX_LINES)
        no = MAX_LINES;

    for (int i = 0; i < no; i++) {
    Line x;
        cout << "Enter line number : ";
        cin >> line;
        cout << "Enter line string : ";
        cin >> input;

        if (x.set(line, input)){
            List[i] = x;
            cout << "Accepted" << endl;
        }
        else
            cout << "Rejected" << endl;

    }
}

void List::display() const {



}
4

3 回答 3

2

List是类型名称而不是成员。你可能是说

this->line[i] = x;

你必须加上前缀,this->因为line单独是模棱两可的,因为你也有

int line;

上面几行(没有双关语)。

为避免命名冲突和使用this->,您可以重命名变量,例如

struct List{
    private:
        struct Line lines[MAX_LINES];
    ...
};

void List::set(int no) {
    int lineno;
    ...
}

this->然后,您可以在不使用或任何其他前缀的情况下进行分配

if (x.set(lineno, input)){
    lines[i] = x;
    cout << "Accepted" << endl;
}
于 2013-02-23T16:59:58.653 回答
1

让我们理解错误消息:

list.cpp: In member function 'void List::set(int)':
list.cpp:23:8: error: expected unqualified-id before '[' token

list.cpp 第 23 行在这里:

List[i] = x;

投诉是:

expected [something] before '[' token

您被告知List您设计的对象不支持该[ ]语法。

于 2013-02-23T17:00:06.803 回答
1

要使此代码正常工作:

List[i] = x;

您的班级列表必须提供 operator[] aka 下标运算符:

class List {
public:
...
   Line &operator[]( int line );
...
};

这是一个示例,它可以返回 const 引用或返回值,成为 const 方法等取决于您的程序。

于 2013-02-23T17:00:57.037 回答