开发者

Member function returning a static variable

Should a member function that returns a static member variable also be static?

For instance:

struct T {
   static int i;
   static开发者_如何学运维 int getNumber() {
       return i;
   }
};

Should getNumber be static or not?


Usually, yes.

If the variable doesn't have any per-instance state, then what possible per-instance logic could the function perform on it before returning it?


It's not compulsory. you can write a member function that returns a static variable. You cannot go the other way around (write a static function which returns an instance variable).

As an example of a case where you may want to return a static member, imagine a circumstance where the class holds a state variable and based on the state you would return one of the static values. Not that this is good design, but its not completely inconceivable

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜