这是循环依赖的问题。幸运的是,这很容易解决:只需将声明和定义放在单独的文件中即可。
ClassA.h:
// Include guards to prevent double includes
#ifndef CLASS_A_H
#define CLASS_A_H
class classA
{
private:
int Value = 100;
public:
// Here we only declare, but not define the functions
int get_Value();
void set_Value(int p);
};
#endif // CLASS_A_H
ClassB.h:
// Include guards to prevent double includes
#ifndef CLASS_B_H
#define CLASS_B_H
class classB
{
private:
int Value = 200;
public:
// Here we only declare, but not define the functions
int get_Value();
void set_Value(int p);
};
#endif // CLASS_B_H
现在我们需要实际定义函数,但是在不同的文件中
ClassA.cpp:
#include "A.h"
#include "B.h"
// Use extern to tell the compiler that this declaration can be
// found in any of the other files and it will not complain as
// long as it is found somewhere
extern classB B;
int classA::get_Value()
{
return Value;
}
void classA::set_Value(int p)
{
if (p == 0) Value = B.get_Value();
else Value = 5;
}
ClassB.cpp:
#include "A.h"
#include "B.h"
// Use extern to tell the compiler that this declaration can be
// found in any of the other files and it will not complain as
// long as it is found somewhere
extern classA A;
int classB::get_Value()
{
return Value;
}
void classB::set_Value(int p)
{
if (p == 0) Value = A.get_Value();
else Value = 5;
}
然后,在你的主文件中只包含两个标题就可以了:
#include "A.h"
#include "B.h"
classB B = classB();
classA A = classA();
顺便说一句,当您使用 Arduino 时,您可以创建新的 .h 和 .cpp 文件并将它们放在 .ino 文件旁边,应该可以找到它。您甚至可以将它们放在文件夹中,但是包含路径必须相对于每个文件,例如:#include "../include/file.h"