【发布时间】:2012-12-14 19:06:39
【问题描述】:
刚刚阅读了友元函数,我正在尝试使用 B 类的友元函数“打印”访问 A 类中的私有变量“数字”。我正在使用 Visual Studio。编译我的代码给了我很多各种错误,例如:
C2011: 'A' : 'class' 类型重新定义
C2653: 'B' : 不是类或命名空间名称
请耐心等待我,并展示实现我目标的正确方法。
这是我的文件 啊哈:
class A
{
public:
A(int a);
friend void B::Print(A &obj);
private:
int number;
};
A.cpp:
#include "A.h"
A::A(int a)
{
number=a;
}
B.h:
#include <iostream>
using namespace std;
#include "A.h"
class B
{
public:
B(void);
void Print(A &obj);
};
B.cpp:
#include "B.h"
B::B(void){}
void B::Print(A &obj)
{
cout<<obj.number<<endl;
}
main.cpp:
#include <iostream>
#include <conio.h>
#include "B.h"
#include "A.h"
void main()
{
A a_object(10);
B b_object;
b_object.Print(A &obj);
_getch();
}
【问题讨论】:
-
提示:
B类实际上不需要知道A的详细信息,它只需要知道A类存在。跨度> -
删除
friend void B::Print(A &obj);,添加friend class B;或按照 Mooning Ducks 提示。 -
在 B.h 中删除
#include "A.h"并添加class A;然后在 B.cpp 中添加#include "A.h"
标签: c++ class friend friend-class