A Question about Friend Function in C++: Define a member function of class A as Friend Function of class B

The problem is as follows:
I have a class Xth, which has a private member damage, and now I want to print this value with another class Badao member function use(); in fact, the problem is very simple.
Clear implementations, such as defining a public function in Xth to get the value of damage, and so on; but my first thought was to play a wave of sauce operations with friend functions.
The problem is that the two classes are written in their respective header files. At first, I thought that the two classes must contain each other's header files, but this can not be compiled at all.

Quote a big man's answer to another similar question:

  • Friend function is obviously possible, but the problem you mentioned is that you can avoid declaring the member function of Manage class as Friend function in Book class, so it is necessary to include the header file of Manage class, and you'd better use early declaration and add a word class Manage.
    The function in the Manage class (which is declared as a friend function) can use the declaration of the Book class, that is to say, only declare the class Book, not include the header file, because there is no need to expand the specific function in the header file, so there is no need to include the header file of the Book class, just need to include the header file of the Book class in the cpp file of the Manage class.
Here is the code
main.cpp:
---------------------------------------------
#include <iostream>
#include "Badao.h"
#include "Xth.h"
using namespace std;

int main()
{
    Badao die;
    Xth one;
    die.use(one);
    cout << "Hello world!" << endl;
    return 0;
}

Xth.h
--------------------------------------------
#ifndef XTH_H
#define XTH_H
#include "Badao.h"
class Badao;
class Xth
{
    friend void Badao::use(Xth &);
    public:
        Xth();
        virtual ~Xth();

    protected:

    private:
        int damage=1000;
};
#endif // XTH_H

Xth.cpp
------------------------------------------
#include "Xth.h"
#include "Badao.h"

Xth::Xth()
{
    //ctor
}

Xth::~Xth()
{
    //dtor
}

Badao.h
------------------------------------------
#ifndef BADAO_H
#define BADAO_H

using namespace std;
class Xth;
class Badao
{
    public:
        Badao();
        void use(Xth &);
        virtual ~Badao();

    protected:

    private:
};

#endif // BADAO_H

Badao.cpp
-----------------------------------------
#include "Badao.h"
#include <iostream>
#include "Xth.h"

Badao::Badao()
{
    //ctor
}
void Badao::use(Xth &cw){
    cout<<cw.damage<<endl;
}
Badao::~Badao()
{
    //dtor
}

Posted by RamboJustRambo on Tue, 26 Mar 2019 17:15:27 -0700