[英]Overloading subscript operator not working as expected
I have a String
struct that I overloaded the subscript operator on.我有一个
String
结构,我在它上面重载了下标运算符。 But it doesn't seem to work.但它似乎不起作用。
//my_string.h
struct String {
char* Text;
uint64 Length;
char& operator[](int32 index);
}
//my_string.cpp
char& String::operator[](int32 index) {
ASSERT(index >= 0);
return Text[index];
}
//main.cpp
String* test = string_create("Hello world");
char c = test[0];
Visual Studio gives me the following error: Visual Studio 给了我以下错误:
no suitable conversion function from "String" to "char" exists
不存在从“String”到“char”的合适转换函数
The compiler issued an error because in this statement编译器发出错误,因为在此语句中
char c = test[0];
the expression test[0]
has the type String
.表达式
test[0]
的类型为String
。
In this declaration在本声明中
String* test = string_create("Hello world");
you declared a pointer instead of an object of the type String.您声明了一个指针而不是 String 类型的对象。
If it is not a typo then in this case you have to write如果它不是错字,那么在这种情况下你必须写
char c = ( *test )[0];
or或者
char c = test->operator []( 0 );
Also it looks strange that the data member Length
has the type uint64
数据成员
Length
的类型为uint64
看起来也很奇怪
uint64 Length;
while the index used in the operator has the type int32
.而运算符中使用的索引的类型为
int32
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.