提问者:小点点

编译器错误,当将指向类的链接作为方法参数时


我试着用C++理解友好的类。 我做了两个类:拉达(汽车)和机械师。 拉达是对机械师友好的类,因此机械师可以查看和更改拉达的私有变量。 当你对Lada进行初始化时,它需要一个参数,bool isBroken(不需要解释)。 而技工班有方法,那就是修理拉达(变坏为假)。 我不知道为什么,但它显示了一个错误:>;

C:\C++\FriendlyClassesTests>c++ Lada.cpp Lada.h Mechanic.cpp Mechanic.h main.cpp -std=c++20
In file included from Lada.h:3:
Mechanic.h:11:25: error: 'Lada' has not been declared
   11 |         void RepairLada(Lada& lada);
      |                         ^~~~
Mechanic.cpp:9:1: error: no declaration matches 'int Mechanic::RepairLada(Lada&)'
    9 | Mechanic::RepairLada(Lada& lada) {
      | ^~~~~~~~
Mechanic.h:11:14: note: candidate is: 'void Mechanic::RepairLada(Lada*)'
   11 |         void RepairLada(Lada& lada);
      |              ^~~~~~~~~~
Mechanic.h:6:7: note: 'class Mechanic' defined here
    6 | class Mechanic
      |       ^~~~~~~~
In file included from Lada.h:3,
                 from main.cpp:2:
Mechanic.h:11:25: error: 'Lada' has not been declared
   11 |         void RepairLada(Lada& lada);
      |                         ^~~~

我在mechanic.cpp和mechanic.h文件中都包含了“lada.h”文件。

mechanic.h文件:

#ifndef MECHANIC_H
#define MECHANIC_H
#include "Lada.h"


class Mechanic
{
    public:
        Mechanic();

        void RepairLada(Lada& lada);

    protected:

    private:
};

#endif // MECHANIC_H

mechanic.cpp文件:

#include "Mechanic.h"
#include "Lada.h"

Mechanic::Mechanic()
{
    // Constructor!
}

Mechanic::RepairLada(Lada& lada) {
    lada.isBroken = false;
}

lad.h文件:https://pastebin.com/7mbd5h0a

lad.cpp文件:https://pastebin.com/fj4pqazw

对不起,如果我的英语有任何错误,我是乌克兰人。 希望得到你的帮助。


共1个答案

匿名用户

这里的错误是您在lada中包含了mechanic,在mechanic中包含了lada,这会导致无限循环,因为编译器不知道应该首先包含哪一个。

您可以使用转发声明LADA中声明Mechanic,而不必包含它:

#ifndef SOMECLASS_H
#define SOMECLASS_H

class Mechanic; // Use this instead of #include
class Lada {
public:
    // ...
};

#endif