Given a pointer to a C++ object, what is the preferred way to call a static member function?
Say I have:
class A {
public:
static void DoStuff();
// ... more methods here ...
};
And later on I have a function that wants to call DoStuff:
B::SomeFunction(A* a_ptr) {
Is it better to say:
a_ptr->DoStuff();
}
Or is the following better even though I have an instance pointer:
A::DoStuff()
}
This is purely a matter of style, but I'd like to get some informed opinions before I make a decision.
我想我更喜欢“A :: DoStuff()”,因为更清楚的是正在调用静态方法。
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.
我个人更喜欢A :: DoStuff()约定,因为任何读取代码的人都会立即清楚它是对静态成员函数的调用。
链接地址: http://www.djcxy.com/p/2848.html上一篇: 代理服务器和反向代理服务器之间的区别