gpt4 book ai didi

c++ - 编译器看不到在类中定义的友元函数

转载 作者:行者123 更新时间:2023-12-01 14:48:06 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What's the scope of inline friend functions?

(6 个回答)


去年关闭。




在编译以下代码时:

class A {
A() = default;
public:
friend A getA() {
return A();
}
};

int main()
{
A a = getA();
}

编译器给了我一个错误:

'getA' was not declared in this scope



这是为什么?

最佳答案

因为friend function getA无法通过名称查找找到。

(强调我的)

A name first declared in a friend declaration within class or class template X becomes a member of the innermost enclosing namespace of X, but is not visible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided


getA找不到 ADL或者,(它没有参数)。您需要在命名空间范围内提供声明。例如
class A;
A getA();
class A {
A() = default;
public:
friend A getA() {
return A();
}
};

关于c++ - 编译器看不到在类中定义的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61360176/

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