[英]C++ error: no match for 'operator[]' (operand types are 'const my_array_over' and 'size_t' {aka 'long unsigned int'})
#include <iostream>
using namespace std;
class my_array_over
{
size_t len = 1;
int *a = new int[1];
public:
my_array_over() { a[0] = 0; }
my_array_over(size_t ln, const int *o) : len(ln), a(new int[ln])
{
for (size_t n = 0; n < ln; ++n)
a[n] = o[n];
}
~my_array_over() { delete[] a; }
size_t get_length() const
{
return len;
}
int get(size_t n) const
{
return a[n];
}
int set(size_t n, int v)
{
int tmp = a[n];
a[n] = v;
return tmp;
}
};
void foo(const my_array_over &a2, size_t i)
{
if (i < a2.get_length())
std::cout << a2[i] << std::endl;
}
Been trying to fix this code but kept getting an error saying "no match for 'operator[]' enter code here
(operand types are 'const my_array_over' and 'size_t' {aka 'long unsigned int'})" on一直在尝试修复此代码,但一直收到错误消息,提示“不匹配 'operator[]'
enter code here
(操作数类型为 'const my_array_over' 和 'size_t' {aka 'long unsigned int'})”
std::cout << a2[i] << std::endl; std::cout << a2[i] << std::endl;
In this statement在这份声明中
std::cout << a2[i] << std::endl;
there is used the subscript operator for an object of the type my_array_over
that (the subscript operator) is not defined within the class.对于
my_array_over
类型的 object 使用下标运算符(下标运算符)未在 class 中定义。 It seems you mean看来你的意思
std::cout << a2.get( i ) << std::endl;
Otherwise you need to define the subscript operator within the class definition.否则,您需要在 class 定义中定义下标运算符。 For example
例如
const int & operator []( size_t n ) const
{
return a[n];
}
int & operator []( size_t n )
{
return a[n];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.