在 C++ 类的另一个头文件中定义的调用函数

Calling function defined in another header file in a class in C++

本文关键字:定义 调用 函数 文件 C++ 另一个      更新时间:2023-10-16

我正在尝试在一个类中使用带有shiftreg.cpp的shiftreg.h(我之前在我的主文件中成功使用过)并调用他的一个函数。可悲的是,is没有编译并给出错误:'shiftWrite'没有在这个范围内声明。我想我将每个头文件都包含在其他每个头文件中,它们应该找到彼此。出了什么问题?

这是 shiftreg.h:

#ifndef shiftreg_h
#define shiftreg_h
void shiftWrite(uint8_t data);
#endif

而这个班次.cpp:

#include "ShiftReg.h"
void shiftWrite(uint8_t data) {
    do something;}

函数shiftWrite,我想在类SegmentDisplay的函数中使用如下,与SegmentDisplay.h

#ifndef SegmentDisplay_h
#define SegmentDisplay_h
#include <ShiftReg/shiftReg.h>
class SegmentDisplay{
public:
    void pickNumber(int x);
};
#endif

和片段播放.cpp:

#include "SegmentDisplay.h"
void SegmentDisplay::pickNumber(int x){
    shiftWrite(ONE);}

这一切都始于Arduino软件:

  #include "SegShift.h"
  SegmentDisplay dsp();
  int main(void){
      while(1){
          dsp.pickNumber(j);}}

您似乎包含两个不同的文件:

在 ShiftReg 中.cpp您可以执行以下操作: #include "ShiftReg.h"

在 SegmentDisplay.h 中,您可以执行#include <ShiftReg/shiftReg.h>

(顺便说一下,我只是在你的SegmentDisplay.cpp中包含shiftreg.h。

我已将 ShiftReg.h 和 ShiftReg.cpp 文件添加到 SegmentDisplay 文件的文件夹中,然后它就可以编译了!我很高兴我也在你的答案的帮助下解决了这个问题。

但是,我想知道为什么当文件位于不同的文件夹中时,我无法使用这些文件。有什么想法吗?

在 SegmentDisplay.h 中,您必须包含 shiftreg.cpp而不是 shiftreg.h

否则,代码看不到声明的函数