gpt4 book ai didi

c++ - 如何在将内部类作为参数的命名空间中声明友元函数?

转载 作者:IT老高 更新时间:2023-10-28 23:21:34 26 4
gpt4 key购买 nike

考虑这段代码:

namespace foo {}

class A
{
class B
{
};

friend int foo::bar( B& );
};

namespace foo
{
int bar( A::B& )
{
}
}

G++ 4.4.3 告诉我:

friendfun-innerclass.cpp:21: error: 'int foo::bar(A::B&)' should have been declared inside 'foo'

但我不能声明:

namespace foo
{
int bar( A::B& );
}

在 A 类定义之前,因为 A::B 尚未声明。而且我显然不能声明“A类::B”,要声明B类,我必须给出A类的定义,据我所知,“ friend ”声明必须在A类的定义中。

对我来说奇怪的是,如果我将函数“bar()”从 namespace foo 中取出,一切正常。对我来说,在命名空间内有一个函数或不在一个命名空间内会改变编译器是否接受类中的友元函数声明,这似乎违反直觉。

有没有人知道一种方法来正确地构造所有的声明等等来让它工作?

最佳答案

不能按照您想要的方式完成,因为您必须转发声明一个嵌套类 ( which you can't ) 才能为 foo::bar 提供原型(prototype).

作为解决此问题的第一次尝试,我可能会求助于 foo::bar一个函数模板。这样编译器将解析 A 之后的类型和 B是已知的。

测试工具:

namespace foo
{
template<class B> int bar(B&);
};

class A
{
class B
{
template<class B> friend int foo::bar( B& );
int n_;
public:
B() : n_(42) {}
};

public:
B b_;
};

template<class B> int foo::bar(B& b)
{
return b.n_;
}

int main()
{
A a;
foo::bar(a.b_);
}

关于c++ - 如何在将内部类作为参数的命名空间中声明友元函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7728405/

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