Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

What does "char fun[](int x) const" do?: C++ Syntax Error

I am following along with a video emulating a cpu in C++. The programmer used the following and it is the first time I encounter it:

This is the code from the video:

struct Mem
{
    Byte Data[MAX_MEM];

    Byte operator[]( u32 Offset ) // <-- I don't understand this syntax
    {
    }
}

I wrote it in my own project like this:

char data[1024*64];
char fun[] ( int x ) const  // <-- Is this right?
{
  return data[x];
}

my issue is with line 1# of the example. They were able to compile but I am met with errors:

incomplete type is not allowed;
array of functions is not allowed;
a type qualifier is not allowed on a nonmember function.

What does this syntax actually do; is there an alternative way to write it?

question from:https://stackoverflow.com/questions/65547111/what-does-char-funint-x-const-do-c-syntax-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...