Friend functions and namespaces. Cannot access private member in class

只谈情不闲聊 提交于 2019-12-02 06:35:57

问题


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.

Question: Why?

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

回答1:


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

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



来源:https://stackoverflow.com/questions/34212750/friend-functions-and-namespaces-cannot-access-private-member-in-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!