通过重载运算符 [] 访问自定义数组包装器中的元素
Accessing element in custom array wrapper via overloading operator []
我正在尝试实现我自己的数组包装器。我重载了 [] 运算符 returns 数组中元素的地址。但是,当我在 main 中动态分配 ArrayWrapper class 时,它不起作用。
为什么不起作用? 是因为变量arr是指针吗?
我收到这些错误:
Description Resource Path Location Type cannot bind 'std::ostream {aka
std::basic_ostream}' lvalue to
'std::basic_ostream&&' Cviceni.cpp /Cviceni/src line 25 C/C++
Problem
Description Resource Path Location Type no match for 'operator<<'
(operand types are 'std::ostream {aka std::basic_ostream}' and
'ArrayWrapper') Cviceni.cpp /Cviceni/src line 25 C/C++ Problem
工作代码
ArrayWrapper arr(250);
try
{
for(int i = 0; i < arr.getSize(); i++)
{
arr[i] = i + 1;
cout << arr[i] << endl;
}
}
catch(std::range_error& e)
{
cout << e.what() << endl;
}
cout << "End..." << endl;
return 0;
}
无效代码:
ArrayWrapper *arr = new ArrayWrapper(250);
try
{
for(int i = 0; i < arr->getSize(); i++)
{
arr[i] = i + 1;
cout << arr[i] << endl;
}
}
ArrayWrapper 实现:
class ArrayWrapper
{
private:
int size;
int *elements;
public:
ArrayWrapper(int n) : size(n), elements(new int[n])
{
for(int i = 0; i < size; i++)
elements[i] = 0;
};
~ArrayWrapper(){delete []elements;};
int& operator[](int i)
{
if(i >= size || i < 0)
{
throw range_error("Out of range");
}
return elements[i];
};
int getSize(){ return size;};
};
是你在第二个例子中使用了指针
arr[2]
不是对 ArrayWrapper 的操作,它是对指针的操作。
ArrayWrapper *arr = new ArrayWrapper(250);
try
{
for(int i = 0; i < arr->getSize(); i++)
{
(*arr)[i] = i + 1;
cout << (*arr)[i] << endl;
}
}
我正在尝试实现我自己的数组包装器。我重载了 [] 运算符 returns 数组中元素的地址。但是,当我在 main 中动态分配 ArrayWrapper class 时,它不起作用。
为什么不起作用? 是因为变量arr是指针吗?
我收到这些错误:
Description Resource Path Location Type cannot bind 'std::ostream {aka std::basic_ostream}' lvalue to 'std::basic_ostream&&' Cviceni.cpp /Cviceni/src line 25 C/C++ Problem
Description Resource Path Location Type no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'ArrayWrapper') Cviceni.cpp /Cviceni/src line 25 C/C++ Problem
工作代码
ArrayWrapper arr(250);
try
{
for(int i = 0; i < arr.getSize(); i++)
{
arr[i] = i + 1;
cout << arr[i] << endl;
}
}
catch(std::range_error& e)
{
cout << e.what() << endl;
}
cout << "End..." << endl;
return 0;
}
无效代码:
ArrayWrapper *arr = new ArrayWrapper(250);
try
{
for(int i = 0; i < arr->getSize(); i++)
{
arr[i] = i + 1;
cout << arr[i] << endl;
}
}
ArrayWrapper 实现:
class ArrayWrapper
{
private:
int size;
int *elements;
public:
ArrayWrapper(int n) : size(n), elements(new int[n])
{
for(int i = 0; i < size; i++)
elements[i] = 0;
};
~ArrayWrapper(){delete []elements;};
int& operator[](int i)
{
if(i >= size || i < 0)
{
throw range_error("Out of range");
}
return elements[i];
};
int getSize(){ return size;};
};
是你在第二个例子中使用了指针
arr[2]
不是对 ArrayWrapper 的操作,它是对指针的操作。
ArrayWrapper *arr = new ArrayWrapper(250);
try
{
for(int i = 0; i < arr->getSize(); i++)
{
(*arr)[i] = i + 1;
cout << (*arr)[i] << endl;
}
}