namespaces, classes and free functions - when do you need fully qualified names

前端 未结 4 1854
醉梦人生
醉梦人生 2021-02-03 13:30

In my example below, why do I have to fully qualify the name of the free function in the cpp to avoid linker errors and why does it work for the class function without? Can you

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-03 13:58

    While FreeFunction will resolve to Test::FreeFunction if you refer to it or call it after providing the using namespace Test; line, as far as defining the function goes, the compiler has no way to know if you're defining an entirely new function FreeFunction outside of any namespace, or whether you're defining the already declared Test::FreeFunction. The compiler defaults to thinking that you're defining an entirely new function.

    For CTest::CTest, however, you're already referring to the class Test::CTest, and since there's no class or namespace CTest outside of the Test namespace, well, the reference to CTest::anything is unambiguous. So it knows that the constructor and destructor definitions refer to the in-namespace class CTest.

    I think it's a small price to pay, to have to write Test::FreeFunction.

    Hope this helps!

提交回复
热议问题