所以我在 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/