朋友函数和命名空间。无法访问类中的私有成员 [英] Friend functions and namespaces. Cannot access private member in class

查看:218
本文介绍了朋友函数和命名空间。无法访问类中的私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在 foo 命名空间中有一个 class ,其中包括 / code>函数。现在我想要 friend 函数的定义在不同的命名空间 bar 中,因此它可以被称为你的方式见下文。我得到的错误是私人成员 val 无法访问。

So I have a class inside a foo namespace, which includes a friend function. Now I want the definition of the friend function to be in a different namespace bar so it can be called the way you see below. The error I get is that the private member val cannot be accessed.

问题:为什么?

#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);
}


推荐答案

$ c> foo :: bar :: myfun 之前的朋友声明并使用适当的命名空间限定( bar :: ):

You should declare foo::bar::myfun before the friend declaration and use appropriate namespace qualification (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 命名空间中声明。

Otherwise another function called myfun will be declared in the foo namespace by the friend declaration.

这篇关于朋友函数和命名空间。无法访问类中的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆