简体   繁体   English

C ++从好友类访问成员函数

[英]C++ access member-function from friend class

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 如果重要的话我用gcc 4.5.2

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. 如果假设get_class_from_item是某种Factory函数,似乎是这样,则需要将其设为静态。 You get the error because your compiler is looking for a function named get_class_from_item in class A . 之所以会出现错误,是因为您的编译器正在类A寻找名为get_class_from_item的函数。 It will never see the function in B because it is not in the scope and you don't have an instance of class B . 它永远不会在B看到该函数,因为它不在范围内,并且您没有类B的实例。 Here is some more explanation on Wikipedia: http://en.wikipedia.org/wiki/Factory_function . 这是有关Wikipedia的更多说明: http : //en.wikipedia.org/wiki/Factory_function

This should do it: 应该这样做:

class A
{
    bool operator()(Item * item)
    {
        ObjectClass c = B::get_class_from_item(item);
        ...
    }
};

class B
{
    static ObjectClass get_class_from_item(Item* item);
};

Also, is there a reason that A needs to be a friend class of B ? 另外,是否有理由A需要成为B的朋友? Or did you just do that trying to get get_class_from_item to work? 还是您只是尝试使get_class_from_item工作? Does A need to be able to access some private elements of B ? A是否需要能够访问B某些私有元素? Think carefully about this, most of the time there are better ways of obtaining what you want instead of throwing away all encapsulation by using friend . 仔细考虑一下,大多数时候,有更好的方法来获取想要的内容,而不是使用friend丢弃所有封装。

[Edit] Removed lines from code example to strip it to the bare minimum. [编辑]从代码示例中删除了几行,以将其剥离到最低限度。

不可以,因为get_class_from_item是成员函数,所以需要B类的实例才能调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM