这里是一段使用友元函数的简单代码:
#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;
}
运行情况如下:
但是问题来了,如果我将这个文件拆成多文件编写,就出问题了(注意:类的声明在.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
一直报错出现下边内容: