Using a namespace in place of a static class in C++?

前端 未结 4 1790
一整个雨季
一整个雨季 2020-12-29 03:29

Is it good or okay practice to use a namespace as a static class? For example:

namespace MyStaticFunctions {
    void doSomething();
}

Vers

4条回答
  •  伪装坚强ぢ
    2020-12-29 04:07

    It depends.

    Is the method logically related to a class? If so, make it a member, otherwise place it in a namespace.

    Functionally, they're the same, but there's more to code than function, right? For example, consider a method that returns the name of the class:

    struct MyClass
    {
        static std::string getName() { return "MyClass"; }
    }
    

    You could obviously place the method outside, in a namespace, and get the same result, but it logically belongs to the class.

提交回复
热议问题