Is it possible to avoid repeating the class name in the implementation file?

后端 未结 8 2056
迷失自我
迷失自我 2020-11-27 21:39

Is there a way to avoid the Graph:: repetition in the implementation file, yet still split the class into header + implementation? Such as in:

Header Fi

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 21:55

    If you are asking if you can define a member function such as Graph::printGraph without specifying the class name qualification, then the answer is no, not the way that you want. This is not possible in C++:

    implementation file:

    void printEdge(){};
    

    The above will compile just fine, but it won't do what you want. It won't define the member function by the same name within the Graph class. Rather, it will declare and define a new free function called printEdge.

    This is good and proper, if by your point of view a bit of a pain, because you just might want two functions with the same name but in different scopes. Consider:

    // Header File
    class A
    {
      void foo();
    };
    
    class B
    {
      void foo();
    };
    
    void foo();
    
    // Implementation File
    void foo()
    {
    }
    

    Which scope should the definition apply to? C++ does not restrict you from having different functions with the same names in different scopes, so you have to tell the compiler what function you're defining.

提交回复
热议问题