简体   繁体   English

编译器如何不将名为 size 的局部变量与 function 调用 size() 混淆?

[英]How does the compiler not confuse local variable named size with function call size()?

While reading a C++ textbook, I came across this specific piece of code:在阅读 C++ 教科书时,我遇到了这段特定的代码:

vector<double> homework;
typedef vector<double>::size_type vec_sz;
vec_sz size = homework.size();

I wonder how isn't there any conflict during compilation since the local variable size and the function being called size() share the same name and (here expecting a correction if I am wrong) they are apparently in the same scope. If they aren't in the same scope, then how does the compiler handle these two names in a single statement?我想知道在编译过程中怎么没有任何冲突,因为局部变量size和被称为size()的 function 共享相同的名称并且(如果我错了,这里期待更正)它们显然在同一个 scope 中。如果他们不是' 在同一个 scope 中,那么编译器如何在一条语句中处理这两个名称?

Thanks for your time in advance I hope my question makes sense!感谢您提前抽出时间,我希望我的问题是有道理的!

how isn't there any conflict during compilation since the local variable size由于局部变量大小,编译期间如何没有任何冲突

Because size in homework.size() is a qualified name .因为homework.size()中的size是一个限定名 While the name size without any qualification is an unqualified name .而没有任何限定的名字size就是不合格的名字 When you wrote homework.size() only the class scope corresponding to the class name homework is searched.当你写homework.size()时,只会搜索 class name homework对应的class scope 。 So there is no clash between the two names if you were to write:因此,如果您要编写,这两个名称之间不会发生冲突:

//----vvvv-------------------->local variable named size
      size = homework.size();
//--------------------^^^^---->data member named size in class scope

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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