Name lookup for Class Member Declarations

It's quoted from the <<C++ primer>>

"""

....

typedef double Money;

string bal;

class Account {

public:

 Money balance() { return bal; }

private:

 Money bal;

//.....

};

When the compiler sees the declaration of the balance function, it will look for a declaration of Money in the Account class. The compiler considers only declarations inside Account that appear before the use of Money. Because no matching member is found, the compiler then looks for a declaration in the enclosing scope(s). In this example, the compiler will find the typedef of Money. That type will be used for the return type of the function balance and as the type for the data member bal. On the other hand, the function body of balance is processed only after the entire class is seen. Thus the return inside that function returns the member named bal, not the string from the outer scope.

"""

The book obviously mentions the name lookup in class, who is closer than the declaration. the compiler would use it at first. Both types are defined in the class or outside of class. the body of function that is in class will call the nearest definition.

In the books, it mentions redefine the typename will cause the error. some compiler will quietly accept such code. Redefinition should be cautioned.


there are three principles for name-lookup

1) First, look for a declaration of the name inside the member function. As usual, only declarations in the function body that precede the use of the name are considered.

2) If the declaration is not found inside the member function, look for a declaration inside the class. All the members of the class are considered.

3) If a declaration for the name is not found in the class, look for a declaration that is in scope before the member function definition.

Ordinarily, it is a bad idea to use the name of another member as the name for a parameter in a member function.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值