c++ - 友元函数和命名空间。无法访问类中的私有(private)成员

标签 c++ class templates friend

所以我在 foo 命名空间中有一个 class,其中包含一个 friend 函数。现在,我希望将 friend 函数的定义放在不同的命名空间 bar 中,以便可以按如下所示的方式调用它。我得到的错误是私有(private)成员val无法访问。

问题:为什么?

#include <iostream>

namespace foo 
{
    template<typename T>
    class myclass
    {
    private:
        T val;
    public:
        myclass(T v) : val(v) {}

        template<class U>
        friend void myfun(myclass<U>);
    };

    namespace bar 
    {
        template<class U>
        void myfun(myclass<U> a)
        {
            std::cout << a.val;
        }
    } //bar
} //foo

int main()
{
    foo::myclass<int> a(5);
    foo::bar::myfun(a);
}

最佳答案

您应该在友元声明之前声明 foo::bar::myfun 并使用适当的命名空间限定 (bar::):

namespace foo 
{
    template<typename T>
    class myclass;

    namespace bar 
    {
        template<class U>
        void myfun(myclass<U> a);
    } //bar

    template<typename T>
    class myclass
    {
    private:
        T val;
    public:
        myclass(T v) : val(v) {}

        template<class U>
        friend void bar::myfun(myclass<U>);
    };

} //foo

否则,另一个名为 myfun 的函数将通过友元声明在 foo 命名空间中声明。

关于c++ - 友元函数和命名空间。无法访问类中的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34212750/

相关文章:

以 vector 作为成员的结构的 C++ 大小

c++ - 我可以在类定义中实例化当前类的新对象吗

c++ - 尝试用值初始化列表但在我使用变量创建大小时不起作用

Swift类多重继承

java - 创建一个不带 'new' 参数的构造函数

c++ - 是否可以防止此代码出现 "copy and paste similar template special case"?

c++ - 扩展 std::list

c++ - 模板中的 `class =` 是什么意思?

c++ - 如何使用 Visual Studio 2013 构建 Boost

c++ - 用户关闭 bb10(z10) 应用程序时,需要很长时间才能访问主屏幕上的应用程序图标