指定一个类成员函数作为另一个类的朋友? [英] Specify a class member function as a friend of another class?

查看:112
本文介绍了指定一个类成员函数作为另一个类的朋友?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据C ++ Primer一书,作者提到我们可以将一个类成员函数指定为另一个类的朋友,而不是整个类(第634页)。

According to the C++ Primer book, the author mentioned that We can specify a class member function as a friend of another class, instead of the entire class (page 634).

然后,我测试了这段代码:

Then, I tested this code:

class A
{
public:
    friend void B::fB(A& a);
    void fA(){}
};
class B
{
public:
    void fB(A& a){};
    void fB2(A& a){};
};

我只是想让fB()成为A类的朋友,而不是整个B类的朋友。但是关于代码产生错误:'B':不是类或名称空间名称
(我正在使用Visual C ++ 2005)

I just wanted the fB() to be friend of class A, not the entire class B. But the about code produced an error: 'B' : is not a class or namespace name. (I am using Visual C++ 2005)

推荐答案

尝试将B定义放在A之前:

Try putting the B definition before A's:

class A; // forward declaration of A needed by B

class B
{
public:
    // if these require full definition of A, then put body in implementation file
    void fB(A& a); // Note: no body, unlike original.
    void fB2(A& a); // no body.
};

class A
{
public:
    friend void B::fB(A& a);
    void fA(){}
};

A 需要完整的 B 。但是, B 需要了解 A ,但不需要完整的定义,因此需要前向声明 A

A needs the full definition of B. However, B needs to know about A, but does not need the full definition, so you need the forward declaration of A.

这篇关于指定一个类成员函数作为另一个类的朋友?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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