Name lookup for Class Member Declarations

来源:互联网 发布:js传值给html 编辑:程序博客网 时间:2024/05/03 01:17

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