我对 C++ 很陌生,所以这可能是一个非常愚蠢的问题,但我很难找到解决方案。我四处寻找答案,TA似乎有逻辑上等效但神秘地工作的代码,我们不知道为什么。
我试图在我的头文件中声明一个数组(名为'array),我不断收到一些奇怪的错误。当我将其公开声明为“int* array;”时 或“int array[];”,构造函数告诉我这是对非静态数据成员的无效使用。当我将它声明为私有时,它抱怨数组的元素是私有的。
该赋值处理运算符重载,并处理具有奇数索引的数组,例如从 -3 到 5。下面是一些与问题相关的代码:
// from the .cpp file
//constructor
IntArray::IntArray(int USER_DEFINED)
{
if (USER_DEFINED < 1)
{
//return some kind of error
}
string name;
setName();
int lower = 0;
int higher = USER_DEFINED - 1;
array = new int[higher - lower];
//int* p = &array[abs(lower)];
}
//overload
int IntArray::operator[](int i)
{
if (i < lower || i > higher)
{
//return some sort of error
}
else
return array[i - lower];
}
//from the .h file
class IntArray {
public:
int* array;
int operator[](int i);
};
//from the driver
void test1() {
cout << "1. Array declared with single integer: IntArray a(10);" << endl << endl;
csis << "1. Array declared with single integer: IntArray a(10);" << endl << endl;
IntArray a(10);
for(int i = a.low(); i <= a.high(); i++)
a[i] = i * 10;
a.setName("a");
cout << a << endl;
csis << a << endl;
wait();
}`
a[i] = i * 10; 是编译器抱怨的地方。
提前感谢您的帮助。