“class” Keyword on Return Type - C++ [duplicate]

2020-03-08 08:12发布

I came across a piece of code that looked like this:

class SomeClass* GetSomeClass()
{
  return _instanceOfSomeClass;
}

What does the "class" keyword do on the return type? I can't find anywhere that explains what it's function is. Does it just specify that it's talking about SomeClass as a class in case there is some sort of ambiguousness or something? I am confused.

标签: c++
3条回答
家丑人穷心不美
2楼-- · 2020-03-08 08:21

It is used to disambiguate.

Say for example if you have a variable of the same name in the same (or outer) scope, something like this:

int SomeClass; //SomeClass is declared to be variable here

class SomeClass* GetSomeClass()
{
  return _instanceOfSomeClass;
}

Without the class keyword, the function declaration wouldn't make sense to the compiler. The class keyword tells the compiler to ignore the variable declaration, and look for a class declaration.

查看更多
Luminary・发光体
3楼-- · 2020-03-08 08:28

class SomeClass is a longhand way of referring to the class type SomeClass (technically, it's the elaborated type specifier). Usually, adding class is redundant, and the two are equivalent. But it's sometimes necessary to resolve the ambiguity, if there's a variable or function with the same name.

查看更多
地球回转人心会变
4楼-- · 2020-03-08 08:34

It's a forward declaration. It allows you to just say "there is a class SomeClass somewhere in my program, it is just not visible to this file in order to prevent redeclerations".

Whenever you implement this function, though, the file must have actual interface of class SomeClass.

查看更多
登录 后发表回答