简体   繁体   中英

Accessing a member variable is optimal or accessing a member function

我想知道,哪一种是通过对象指针访问类的成员变量(因为我正在通过朋友功能概念访问它)或通过使用类的getter和setter方法是最佳选择。

To me, the best is an inline getter.

inline int GetValue() const {return Value;}

By the way, you can take a look at this answer

Typically, you'd write getters and setters inline, so there should be no overhead. Even with a separate definition, a good compiler should inline these calls through whole program optimization.

If this is not the case though, profile and see if performance is actually affected before you take any decision.

Note though that accessing members from outside (directly, from a friend or even getters and setters) breaks encapsulation. The friend option limits this to a specific class, so WRT this it's slightly better. If you must access those members, go with friend . If you have tons of friends, better go with getters/setters (at least you have a single access point, right). If performance is an issue (measurable), go with public members.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM