相关知识:
类中成员函数变量名的查找顺序先后为:
- 成员函数中的局部变量;
- 类的成员变量;
- 全局变量;
一个类的编译顺序:
- 从上到下依次编译变量,类型别名,函数声明及其返回值和形参;
- 当上一步完成时,再编译成员函数的函数体。
这也就解释了为什么成员函数可以访问成员变量,即使这个变量是放在类的最末尾(后于这个成员函数定义)。原因就是编译器先编译整个类(除成员函数的函数体),然后再编译成员函数体。
还解释了为什么在类中重命名一些类型尽量放到类的最开始处。因为类中的除成员函数体之外都是顺序编译的,如果不把类型重命名放到使用该重命名的类型之前,那么编译器就不会认识这个重命名的类型。
代码涉及的内容:
类作用域:
使用类的成员;
作用域与成员定义;
形参表和函数体处于类作用域中;
函数返回类型不一定在类作用域中;
类作用域中的名字查找:
类成员声明的名字查找;
类成员定义中的名字查找;
类成员遵循常规的块作用域名字查找;
函数作用域之后,在类作用域中查找;
类作用域之后,在外围作用域中查找;
1 |
|
运行结果:
不报错即可,只是为了对一些作用域的用法进行验证,可以修改程序进行一些输出;