Given a pointer to a C++ object, what is the preferred way to call a static member function?

前端 未结 7 1881
挽巷
挽巷 2020-12-21 04:56

Say I have:

class A {
public:
    static void DoStuff();

    // ... more methods here ...
};

And later on I have a function that wants to

7条回答
  •  庸人自扰
    2020-12-21 05:25

    It's better to call the static method by its name, not through an object, since it doesn't actually use that object at all. In Java, the same problem exists. A not-too-uncommon problem in Java is the following:

    Thread t = getSomeOtherThread();
    t.sleep(1000);
    

    This compiles fine but is almost always an error -- Thread.sleep() is a static method that causes the current thread to sleep, not the thread being acted on as the code seems to imply.

提交回复
热议问题