我是C ++编程的初学者,我现在正在学习有关类和对象的所有知识。为了练习,我创建了一个名为Employee的类,并在其中添加了一些成员。但是我注意到记录数组给我一个错误,指出非静态成员引用必须相对于特定对象。仅当我在Employee类中创建数组时,才会发生这种情况。但是当我在构造函数Employee()
中调用它时,它并没有突出显示为错误,也没有尝试将其初始化为main.cpp中的全局变量甚至本地变量(在{ {1}}位于)。为此,请提供建议甚至更好的解决方案。
main()
main.cpp:
#pragma once
#include<string>
#include<iostream>
using namespace std;
class Employee
{
private:
int recordSize = 100;
int fieldSize = 4;
string record[recordSize][fieldSize];
public:
Employee();
~Employee();
};
我还包括了employee-info.txt的内容
#include "Employee.h"
#include<string>
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
Employee::Employee() {
ifstream inFile;
inFile.open("C:\\Users\\RJ\\Desktop\\employee-info.txt");
for (int index = 0; index < recordSize; index++) {
for (int index2 = 0; index2 < fieldSize; index2++) {
inFile >> record[recordSize][fieldSize];
}
}
}
Employee::~Employee()
{
}
答案 0 :(得分:3)
变量recordSize
和fieldSize
必须同时为static
和const
(或constexpr
)才能用作std::string record
的尺寸2D阵列。
它们必须为const
,因为数组绑定应为整数常量。
它们必须为static
,因为对于record
类的不同实例,不允许Employee
数组具有不同的大小。
如果希望2D数组在Employee
类的不同实例中可以容纳不同的大小,则应改用std::vector
的{{1}}。
答案 1 :(得分:-1)
在用于定义数组大小时,大小必须为constexpr
static constexpr int recordSize = 100;
static constexpr int fieldSize = 4;
string record[recordSize][fieldSize];