7-3 名字查找与类的作用域
7.4.0 类定义时的处理流程
- 先编译成员的声明
- 所有成员可见后,编译函数体
7.4.1 一般的名字查找流程
- 在所在块内寻找声明,只找名字之前的部分
- 没找到则去外层作用域找
7.4.2 类成员的名字查找
同一般的名字查找流程,现在类内找,没找到再去外层找
typedef double Money;
string bal;
class Account{
public :
Money balance() {return bal;}
private :
Money bal;
// ...
};
先编译Acount类内的成员 bal, bal的类型是Money,现在类内寻找Money的声明,没有找到,则去类外找,找到了typedef double Money
。
编译完成员后编译函数体return bal;
,现在类内寻找bal
,找到Money bal
,所以此时的返回的是Money bal
而不是string bal
。
7.4.3 类成员函数定义中的名字查找
- 现在成员函数内查找
- 再在类内查找
- 最后去外层作用域查找
int height = 1;
class text{
public :
void h(int height){
cout<<height; //输出的是参数height
}
private :
int height = 3;
};
int main(){
text t;
t.h(2); //输出:2
return 0;
}
#include<iostream>
using namespace std;
int height = 1;
class text{
public :
void h(int ht){
cout<<height; //输出的是类成员height
}
private :
int height = 3;
};
int main(){
text t;
t.h(2); //输出:3
return 0;
}
#include<iostream>
using namespace std;
int height = 1;
class text{
public :
void h(int ht){
cout<<height; //输出的是全局变量height
}
private :
int HT = 3;
};
int main(){
text t;
t.h(2); //输出:1
return 0;
}
成员参数的参数,类成员以及全局变量的名词尽量不要相同
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用