在C ++中使用friend函数
只是阅读朋友的功能,我试图访问私人变量数字在类A的朋友功能打印从类B.我使用Visual Studio。编译我的代码给我很多错误,如:
Just read about friend functions and I'm trying to access private variable "number" in class A with friend function "Print" from class B. I'm working with Visual Studio. Compilation of my code gives me plenty of various errors like:
C2011:'A':'类'类型重新定义
C2653:'B':不是类或命名空间名称
C2011: 'A' : 'class' type redefinition
C2653: 'B' : is not a class or namespace name
请耐心等待我,实现我的目标。
Please be patient with me me and show a proper way of achieving my goal.
这是我的文件
Ah:
Here are my files A.h:
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;
}
Bh:
#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();
}
需要在 Ah
头文件中的 B
类的前向声明来引用 B
作为朋友:
... Second you might need a forward declaration of class B
in the A.h
header file to refer B
as a friend:
#ifndef _A_H_
#define _A_H_
class B;
class A
{
friend class B;
};
#endif
UPDATE
>>
这是不可能的。创建成员函数 friend
声明,可以将全局函数或整个类声明为friend,另请参见: C ++ ref,友谊和继承。
It's not possible to create member function friend
declarations, you can either declare global functions or whole classes as friend, see also: C++ ref, Friendship and inheritance.
一般来说,使用 friend
,因为它强烈地将类耦合在一起。更好的解决方案是耦合接口(不需要公开显示)。
在极少数情况下,它可能是一个好的设计决策,但几乎总是适用于内部细节。
In general it's not a good design idea to use friend
at all, because it strongly couples the classes together. The better solution will be to couple interfaces (which don't need to be publicly visible anyways).
In rare cases it might be a good design decision but that almost always applies to internal details.