【发布时间】:2019-05-16 15:09:13
【问题描述】:
让我先说我来自 Java 背景,所以如果我在这里犯了一些愚蠢的错误,请原谅我......
我正在编写一个 C++ 库,我希望它与 Arduino 和 RaspberryPi 兼容。大多数代码只是干净的标准 C++,但有一些函数是特定于硬件的(例如 GPIO 调用)。作为一个 Java 背景,我想,我将创建一个 HAL 接口来定义那些特定于硬件的功能,然后我可以为 RPi 和 Arduino 创建该接口的实现,结果发现接口不是一个东西在 C++ 中,您必须使用虚拟方法。 请在我的问题底部查看我的源文件。
但是,当我实际使用它时,我发现了一个很奇怪的东西:在堆上使用 HAL 编译,但在堆栈上使用它却没有
//THIS DOES NOT COMPILE
MyLibraryHAL hal = HAL_RaspberryPi();
hal.someHwSpecificFunction(65);
//BUT THIS DOES
MyLibraryHAL* hal = new HAL_RaspberryPi();
hal->someHwSpecificFunction(65);
错误是:src.ino:67: undefined reference to MyLibraryHAL::someHwSpecificFunction(unsigned char)。
这是为什么?这只是虚拟方法工作方式的一个特征吗?还是我在这里遗漏了一些概念?
MyLibraryHAL.h
#include <stdint.h>
#ifndef MyLibraryHAL_h
#define MyLibraryHAL_h
class MyLibraryHAL
{
public:
virtual void someHwSpecificFunction(uint8_t param);
};
#endif
HAL_Arduino.h
#include <stdint.h>
#include "MyLibraryHAL.h"
#ifndef HAL_Arduino_h
#define HAL_Arduino_h
class HAL_Arduino : public MyLibraryHAL
{
public:
void someHwSpecificFunction(uint8_t param);
};
#endif
HAL_Arduino.cpp
#include <stdint.h>
#include "HAL_Arduino.h"
void HAL_Arduino::someHwSpecificFunction(uint8_t param)
{
//do things
}
HAL_RaspberryPi.h
#include <stdint.h>
#include "MyLibraryHAL.h"
#ifndef HAL_RaspberryPi_h
#define HAL_RapsberryPi_h
class HAL_RaspberryPi : public MyLibraryHAL
{
public:
void someHwSpecificFunction(uint8_t param);
};
#endif
HAL_RaspberryPi.cpp
#include <stdint.h>
#include "HAL_RaspberryPi.h"
void HAL_RaspberryPi::someHwSpecificFunction(uint8_t param)
{
//do things
}
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: c++ virtual-functions