开发者

.(dot) access to static method

Following is a popular code:

class A
{
public:
    static const string TYPE = "AEvent";
    const string& getType() { return TYPE; }
};

Above code could be use like this:

if (aInstance.getType() == A::TYPE)
{ 
 开发者_如何学编程   ...
}

It's fine. But it's not intuitiveness. Did not? Look at the next code:

class A
{
public:
    static const string& getType() 
    {
        static const string TYPE = "AEvent";
        return TYPE;
    }
}
//Usage
if (aInstance.getType() == A::getType())
    ....

Of course, getType is static method but it's possible to access dot operator and It's more intuitively see to me.

How do you think about?


If it's clearer to use obj.static_member (or method), then use it; this is often true when the type name is long, such as with templates. Otherwise use Type::static_member.


As long as you're returning a static variable from static method it should be fine. It doesn't matter if you call it using dot or resolution operator. Either way it's part of the object as well as the class which should give you the same static variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜