【问题标题】:C++: granting member function friendship forward declaration?C++:授予成员函数友谊前向声明?
【发布时间】:2012-12-09 06:45:57
【问题描述】:

我对 C++ 中的友谊有疑问。我有两个类,A 和 B,其中 B 的定义使用了 A 的某个实例。我还想让 B 中的成员函数访问 A 中的私有数据成员,从而授予它友谊。但现在的难题是,对于 A 类定义中的友谊声明,B 类尚未定义,因此 IDE(VS 2010)不知道该怎么做。

#include <iostream>
using namespace std;

class B;

class A {
    friend int B::fun(A A);//B as yet undefined here
    int a;
};

class B {
    int b;
public:
    int fun(A inst);
};

int B::fun(A A)
{
    int N = A.a + b;//this throws up an error, since a is not accessible
    return N;
}

我查看了Why this friend function can't access a private member of the class?,但那里关于使用class B; 的前向声明的建议似乎不起作用。我怎样才能直接解决这个问题(即不诉诸于让class B成为class A的朋友,或者让B继承自A或引入getA()函数)?我还查看了Granting friendship to a function from a class defined in a different header,但我的课程在一个 .cpp 文件中(最好保持这种方式),而不是在单独的头文件中,而且我不想授予整个班级的友谊。同时,C++ Forward declaration , friend function problem 提供了一个稍微简单的问题的答案——我不能只更改定义的顺序。同时http://msdn.microsoft.com/en-us/library/ahhw8bzz.aspx提供了另一个类似的示例,但是示例无法在我的计算机上运行,​​所以我需要检查一些编译器标志什么的吗?

【问题讨论】:

    标签: c++ friend access-control forward-declaration


    【解决方案1】:

    换一下?

    class A;
    
    class B
    {
    public:
    int fun(A inst);
    private:
    int b;
    };
    
    class A
    {
    friend int B::fun(A A);
    private:
    int a;
    };
    
    int B::fun(A A)
    {   int N = A.a + b;
    return N;
    }
    

    【讨论】:

    • 这还不够,还有循环依赖
    • 应该可以,因为 fun(A inst); B 类内部刚刚声明但尚未定义。这是有效的,因为您可以将不完整的类型作为函数声明的参数。
    • 啊 ^^ 你是对的 - 我完全忘记了在切换它之后我仍然可以使用class A; 的前向声明,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2019-08-04
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多