Arduino C++ 类需要彼此

问题描述

这里有一个与我的问题相关的例子:

class classA
{
private:
    int Value = 100;

public:
    int get_Value()
    {
        return Value;
    }
    void set_Value(int p)
    {
        if (p == 0) Value = B.get_Value();
        else Value = 5;
    }
};

classA A = classA();

class classB
{
private:
    int Value = 200;

public:
    int get_Value()
    {
        return Value;
    }
    void set_Value(int p)
    {
        if (p == 0) Value = A.get_Value();
        else Value = 5;
    }
};

classB B = classB();

问题是 A 类无法访问 B 类,因为它的定义低于它自己的定义。我的问题是如何定义它以便 A 类可以访问 B 类。 在 classA 开始之前,我尝试了诸如 class classB;class classB; classB B = classB; 之类的东西。

因为我对编程比较陌生,所以我不知道如何解决这些(可能很简单)的问题。希望得到一些帮助!

解决方法

这是循环依赖的问题。幸运的是,这个问题很容易解决:只需将声明和定义放在单独的文件中即可。

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"