Declaring a variable with "class " keyword vs Declaring one without "class" keyword in function signatures

StackOverflow https://stackoverflow.com/questions/21880389

What is the difference between the two methods?

Sometimes when I get compile-time errors complaining that the compiler does not recognize some class types in function signatures, then if I add the keyword "class" in front of the respective variables, it can always solve this kind of compile-time errors.

For example, if the compiler does not recognize the type Client in

void recv( Client * c )

then if I change it to

void recv( class Client * c )

the problem is solved.

I am sorry that I cannot come up with a concrete example as I randomly came up with this question.

有帮助吗?

解决方案

Using keyword class, struct, enum in a type parameter declaration is called elaborated type specifier. It introduces the new type in the scope where the function is declared. It is similar to forward declaration.

There is also another using of such a declaration. For example if a name of an object or a function name hides a class or enum with the same name. For example

struct A {};

A A; // now A is seen as an identifier of the object

void f( struct A );

其他提示

In this case

void recv(Client * c)

Compiler looks for declaration of Client. If it cannot find, it will give error. You can solve it by forward declaration as shown following

class Client;
void recv(Client * c)

Although I have never seen second case, but it looks like that is also declaring class Client here.

If you need to prefix your parameter with class, it means that the compiler is not yet aware of a class called Client. Take the following contrived example:

int main(int argc, char *argv[])
{
   MyClass m;

   return 0;
}

class MyClass
{
};

Because MyClass is declared AFTER the main function, the main function is not aware of the class called MyClass when it tries to create the variable m, and your program would refuse to compile.

To solve this, you would typically use a forward declaration:

class MyClass; // <-- Forward declare MyClass.

int main(int argc, char *argv[])
{
   MyClass m;

   return 0;
}

class MyClass
{
};

In your case, the use of the class keyword before the function parameter's type is essentially forward declaring the class name for you.

The compiler must know the type of the function parameter. Since you obviously don't provide a definition for example by including the header of Client you have to provide a forward declaration. That is what you do in the second example (in an unusual way), so the compiler knows, that Client is a class. Since you only use a Pointer, the declaration is enough and you don't need the definition at this point.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top