从成员函数引用数据成员时出错
Trouble referencing data member from member function
第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方法等取决于您的程序。
相关文章:
- 用于访问容器<T>数据成员的正确 API
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 数据成员SFINAE的C++17测试:gcc vs clang
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 静态数据成员模板专用化的实例化点在哪里
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 使用指针访问数组中的对象数据成员
- 友元函数无法访问私有数据成员 (c++)
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 将私有数据成员添加到野牛生成的类中
- 输入数据成员未按要求工作
- 二维矢量数据成员
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 调用在 HXX 文件中声明的静态数据成员
- 是否可以根据其数据成员的类型确定类型的大小
- 将私有数据成员作为默认参数传递给该类的公共方法时出错
- 使用非静态数据成员和嵌套类构造函数的类内初始化时出错
- 从成员函数引用数据成员时出错