gpt4 book ai didi

c++ - 为什么我们可以从 C++ 中的成员函数访问非成员函数

转载 作者:行者123 更新时间:2023-11-28 04:16:15 25 4
gpt4 key购买 nike

以下代码编译时没有任何警告或错误:

#include <iostream>
using namespace std;
class demo_class
{
int x;
float y;
public:
void fun(void);
};
void fun2(void)
{
cout<<"i am fun2\n";
}
void demo_class::fun(void)
{
cout<<"i am fun\n";
cout<<"i can call fun2\n";
fun2();
}
int main()
{
demo_class ob1;
ob1.fun();
return 0;
}

我不明白,因为 fun 函数的范围只在 demo_class 中那它怎么调用fun2函数,难道不是只在demo_class中访问fun函数才报错吗?

最佳答案

Name lookup将尝试检查所有可能的范围,直到在任何范围内至少找到一个范围,然后名称查找停止。

在这种情况下,名称 fun2 无法在类范围内找到,然后进一步的范围,即检查全局范围并找到 ::fun2

关于c++ - 为什么我们可以从 C++ 中的成员函数访问非成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56539604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com