gpt4 book ai didi

c++ 与成员变量同名的内联友元函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:06 25 4
gpt4 key购买 nike

这让我很吃惊。这有效:

struct foo {
int x;
friend int x(foo f) { return f.x; }
friend int y(foo f);
};

int y(foo f) { return x(f); } // no problem

但这是一个错误:

struct foo {
int x;
friend int x(foo f) { return f.x; }
friend int y(foo f) { return x(f); } // error: invalid use of foo::x data member
};

为什么这两个(禁止)都不允许?

最佳答案

原因是在第一种情况下,友元将函数声明注入(inject)到封闭的命名空间中,因此对 x 的全局范围调用只能看到一个 x .

在第二个示例中,x 在该范围内有两个 含义:全局友元函数和变量(可能隐藏全局友元函数)。

关于c++ 与成员变量同名的内联友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17867285/

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