"char fun[](int x) const" 做什么?:C++ 语法错误
What does "char fun[](int x) const" do?: C++ Syntax Error
我是following along with a video emulating a cpu in C++。程序员用了下面的,第一次遇到:
这是视频中的代码:
struct Mem
{
Byte Data[MAX_MEM];
Byte operator[]( u32 Offset ) // <-- I don't understand this syntax
{
}
}
我在自己的项目中是这样写的:
char data[1024*64];
char fun[] ( int x ) const // <-- Is this right?
{
return data[x];
}
我的问题与示例的第 1#
行有关。他们能够编译,但我遇到了错误:
incomplete type is not allowed;
array of functions is not allowed;
a type qualifier is not allowed on a nonmember function.
这个语法实际上是做什么的;有其他的写法吗?
您的最小示例不太正确;他们在视频中使用的语法非常特殊,您已经更改了一些关键部分 - 他们将索引运算符重载为 class 的成员。发生的事情的一个愚蠢的最小示例如下:
struct X {
char data[1024];
char& operator[](int index) {
return data[index];
}
};
您以后可以在其中编写代码,例如
X x;
x[5] = 'a';
代码段 x[5]
将调用您的用户定义的 operator[]
并将 5
作为参数传递。这里的重点是,本质上,class 中函数的名称是 operator[]
- 这只是一些与 C++ 的 运算符重载 [=33] 特性相关的特殊名称=].可以通过这种方式定义一些固定的其他运算符集 - 您还会看到 operator()
是您希望为用户定义类型 X
或 [ 的对象定义 x(a,b,c,...)
=19=] 如果你想定义 x+y
。请注意 operator
是一个关键字 - 它的名称不能与其他名称互换。此外,对于索引运算符(以及其他一些),此类函数只能在 classes 中定义(尽管某些函数,例如 operator+
可以在 classes 之外定义)。
this 问题中有关于重载的很好的一般参考。
我是following along with a video emulating a cpu in C++。程序员用了下面的,第一次遇到:
这是视频中的代码:
struct Mem
{
Byte Data[MAX_MEM];
Byte operator[]( u32 Offset ) // <-- I don't understand this syntax
{
}
}
我在自己的项目中是这样写的:
char data[1024*64];
char fun[] ( int x ) const // <-- Is this right?
{
return data[x];
}
我的问题与示例的第 1#
行有关。他们能够编译,但我遇到了错误:
incomplete type is not allowed;
array of functions is not allowed;
a type qualifier is not allowed on a nonmember function.
这个语法实际上是做什么的;有其他的写法吗?
您的最小示例不太正确;他们在视频中使用的语法非常特殊,您已经更改了一些关键部分 - 他们将索引运算符重载为 class 的成员。发生的事情的一个愚蠢的最小示例如下:
struct X {
char data[1024];
char& operator[](int index) {
return data[index];
}
};
您以后可以在其中编写代码,例如
X x;
x[5] = 'a';
代码段 x[5]
将调用您的用户定义的 operator[]
并将 5
作为参数传递。这里的重点是,本质上,class 中函数的名称是 operator[]
- 这只是一些与 C++ 的 运算符重载 [=33] 特性相关的特殊名称=].可以通过这种方式定义一些固定的其他运算符集 - 您还会看到 operator()
是您希望为用户定义类型 X
或 [ 的对象定义 x(a,b,c,...)
=19=] 如果你想定义 x+y
。请注意 operator
是一个关键字 - 它的名称不能与其他名称互换。此外,对于索引运算符(以及其他一些),此类函数只能在 classes 中定义(尽管某些函数,例如 operator+
可以在 classes 之外定义)。
this 问题中有关于重载的很好的一般参考。