从成员函数引用数据成员时出错

Trouble referencing data member from member function

本文关键字:出错 数据成员 引用 成员 函数      更新时间:2023-10-16

第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 Processorn==============" << endl;
    cout << "Enter number of items : ";
    cin  >> no;
    list.set(no);
    list.display();
}

这是清单。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;
};

这是第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;
};

这是列表.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 {

}

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;
}

让我们了解错误消息:

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对象不支持[ ]语法。

要使此代码工作:

List[i] = x;

您的类List必须提供运算符[],也就是下标运算符:

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

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