C++从友元类访问成员函数
有没有办法从友元类访问成员函数?
// foo.h
template<typename T>
class A
{
bool operator()(Item* item)
{
ObjectClass c = get_class_from_item(item); // compiler error
...
}
};
class B
{
...
template<typename T> friend class A;
...
ObjectClass get_class_from_item(Item* item);
};
如果重要的话我使用 gcc 4.5.2
Is there a way to access member-function from the friend class?
// foo.h
template<typename T>
class A
{
bool operator()(Item* item)
{
ObjectClass c = get_class_from_item(item); // compiler error
...
}
};
class B
{
...
template<typename T> friend class A;
...
ObjectClass get_class_from_item(Item* item);
};
If it matters I use gcc 4.5.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
get_class_from_item
应该是某种工厂函数(看起来确实如此),那么您需要将其设为静态。您收到此错误是因为您的编译器正在类A
中查找名为get_class_from_item
的函数。它永远不会在B
中看到该函数,因为它不在作用域内,并且您没有类B
的实例。以下是维基百科的更多解释: http://en.wikipedia.org/wiki/Factory_function 。这应该可以做到:
另外,是否有理由
A
需要成为B
的友元类?或者您只是试图让get_class_from_item
工作?A
是否需要能够访问B
的某些私有元素?仔细想想,大多数时候有更好的方法来获得你想要的东西,而不是使用friend
扔掉所有封装。[编辑] 从代码示例中删除了几行,以将其精简到最低限度。
If
get_class_from_item
is supposed to be some kind of Factory function, which it seems to be, you need to make it static. You get the error because your compiler is looking for a function namedget_class_from_item
in classA
. It will never see the function inB
because it is not in the scope and you don't have an instance of classB
. Here is some more explanation on Wikipedia: http://en.wikipedia.org/wiki/Factory_function.This should do it:
Also, is there a reason that
A
needs to be a friend class ofB
? Or did you just do that trying to getget_class_from_item
to work? DoesA
need to be able to access some private elements ofB
? Think carefully about this, most of the time there are better ways of obtaining what you want instead of throwing away all encapsulation by usingfriend
.[Edit] Removed lines from code example to strip it to the bare minimum.
不,由于
get_class_from_item
是一个成员函数,因此您需要类B
的实例才能调用它。No, since
get_class_from_item
is a member function you need an instance of classB
to call it.