FifthDesign 2022-03-07 18:29 采纳率: 83.3%
浏览 58
已结题

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

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

#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

  • 写回答

2条回答 默认 最新

  • stone_wangzx 2022-03-07 19:01
    关注

    你的代码是因为头文件嵌套包含了,修改一下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
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月15日
  • 已采纳回答 3月7日
  • 创建了问题 3月7日