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

后端 未结 4 999
抹茶落季
抹茶落季 2021-01-12 18:58

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 functi

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 19:55

    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.

提交回复
热议问题