Using friend function in C++

半城伤御伤魂 提交于 2019-12-11 03:46:42

问题


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' : '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.

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;
}

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();
}

回答1:


... 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
I'm currently not so sure if it's possible to declare member functions as friends, I'll have a look.

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.

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.




回答2:


First you need to put

#ifndef A_H
#define A_H
.... your A-class definition
#endif

in your A.h and analogous in B.h, so that multiple includes of the same file is prevented (that is your duplicate definition error)...



来源:https://stackoverflow.com/questions/13884788/using-friend-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!