友元函数的使用如何实现多文件编写?

这里是一段使用友元函数的简单代码:

#include <iostream>
using namespace std;
class Wheel;
class Car {
private:
    int size = 6;
public:
    void show(Wheel *wheel);
};

class Wheel {
    friend void Car::show(Wheel *wheel);

private:
    int radius = 2;
};

void Car::show(Wheel *wheel) {
    std::cout << wheel->radius + size;
}

int main() {
    Car car;
    Wheel wheel;
    car.show(&wheel);

    return 0;
}

运行情况如下:

img

但是问题来了,如果我将这个文件拆成多文件编写,就出问题了(注意:类的声明在.h文件,类的功能在.cpp文件)。

//main.cpp
#include <iostream>
using namespace std;
include "Car.h"
include "Wheel.h"

int main() {
    Car car;
    Wheel wheel;
    car.show(&wheel);
    return 0;
}

//Wheel.cpp
#include "Wheel.h"
#include <iostream>
void Car::show(Wheel *wheel) {
    std::cout << wheel->radius + size;
}

//Wheel.h
#ifndef TEXT_WHEEL_H
#define TEXT_WHEEL_H

#include "Car.h"
class Wheel {
    friend void Car::show(Wheel *wheel);
private:
    int radius = 2;
};
#endif //TEXT_WHEEL_H

//Car.h
#ifndef TEXT_CAR_H
#define TEXT_CAR_H

#include "Wheel.h"
class Car {
private:
    int size = 6;
public:
    void show(Wheel *wheel);
};
#endif //TEXT_CAR_H

一直报错出现下边内容:

img

你的代码是因为头文件嵌套包含了,修改一下car.h中的#include “Wheel.h”为class Wheel;

//main.cpp
#include <iostream>
using namespace std;
include "Car.h"
include "Wheel.h"
 
int main() {
    Car car;
    Wheel wheel;
    car.show(&wheel);
    return 0;
}
 
//Car.cpp
#include "Wheel.h"
#include <iostream>
void Car::show(Wheel *wheel) {
    std::cout << wheel->radius + size;
}
 
//Wheel.h
#ifndef TEXT_WHEEL_H
#define TEXT_WHEEL_H
 
#include "Car.h"
class Wheel {
    friend void Car::show(Wheel *wheel);
private:
    int radius = 2;
};
#endif //TEXT_WHEEL_H
 
//Car.h
#ifndef TEXT_CAR_H
#define TEXT_CAR_H
 
//#include "Wheel.h"//修改为 class Wheel;
class Wheel;
class Car {
private:
    int size = 6;
public:
    void show(Wheel *wheel);
};
#endif //TEXT_CAR_H

friend void Car::show(Wheel *wheel);用友元类friend class Car;替换
另外头文件不要循环包含。对于一个类的指针和引用类型,可以直接在前面声明一下该类即可(比如在Car类前面声明class Wheel;),不必包含相应头文件(去掉#include "Wheel.h")。同样Wheel.h也没必要包括Car.h