【问题标题】:Arduino C++ classes needing each other相互需要的 Arduino C++ 类
【发布时间】:2020-12-20 18:49:59
【问题描述】:

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

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 类。 在 A 类开始之前,我尝试了 class classB;class classB; classB B = classB; 之类的东西。

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

【问题讨论】:

标签: class arduino arduino-c++


【解决方案1】:

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

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"

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
相关资源
最近更新 更多