'class' keyword in variable definition in C++

前端 未结 3 1348
天命终不由人
天命终不由人 2020-12-17 10:59

Before anyone asks, yes, this is part of a homework, and yes, I did a lot of Googling before asking. I spent the last hour searching intensively on Google with many, many di

3条回答
  •  佛祖请我去吃肉
    2020-12-17 11:23

    The words "inline forward declaration" need to be mentioned here!

    A forward declaration is simply a way to tell the compiler about a type name before its actually defined. You find these in header files all the time.

    // MyStruct.h
    class MyClass;
    
    struct MyStuct {
       MyClass* m_myClass;
       void foo();
    }
    
    // MyStruct.cpp
    #inlude "MyClass.h"
    void MyStruct::foo() { m_myClass->SomeFunc(); }
    

    Notice that the header file only declares MyClass as a class identifier, and has no idea what it actually is until its defined via the #include in the cpp file. This is forward declaration.

    inline forward declaration is really the same thing, but you simply do it all on one line. This is the same exact code achieving the same thing.

    // MyStruct.h
    struct MyStuct {
       class MyClass* m_myClass;
       void foo();
    }
    
    // MyStruct.cpp
    #inlude "MyClass.h"
    void MyStruct::foo() { m_myClass->SomeFunc(); }
    

    I feel like most programmers prefer the standard forward declaration method (less typing overall usually). Which is why it can be confusing when stumbling upon the lesser used inline version.

    I see many of the answers here calling it an optional keyword, but in the above context of inline forward declaration, it is very much not optional, and will result in compile errors due to missing type specifier.

提交回复
热议问题