Your minimal example isn't quite right; the syntax they are using in the video is very particular and you've changed some crucial pieces - they are overloading the indexing operator as a member of a class. A silly minimal example of what's going on is as follows:
struct X {
char data[1024];
char& operator[](int index) {
return data[index];
}
};
where you could later write code such as
X x;
x[5] = 'a';
where the snippet x[5]
will invoke your user defined operator[]
passing 5
as an argument. The important point here is that, essentially, the name of the function in the class is operator[]
- and that that's just some special name related to C++'s feature of operator overloading. There's some fixed set of other operators that can be defined this way - you'll also see operator()
is you want x(a,b,c,...)
to be defined for an object of user-defined type X
or operator+
if you want x+y
to be defined. Note that operator
is a keyword - its name is not interchangeable with others. Also, for the indexing operator (and a few others), such functions may only be defined within classes (though some, such as operator+
can be defined outside of classes).
There's a good general reference on overloading over at this question.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…