我在使用 Arduino 环境中的类定义中的继承方法时遇到问题。我有一个基类 portal
,它由类 gauge
继承,然后 meter
继承自 gauge
。基类有一个方法的定义,但编译器说找不到 meter::method
的定义。
头文件:
#ifndef UIelements_h
#define UIelements_h
#include "Arduino.h"
#include "UTFT.h"
#include "URTouch.h"
#include "UTFT_Geometry.h"
class portal
{
public:
UTFT* myDisplay;
int origin[2]={0,0};
int portalSize[2]={10,10};
int BGColor=VGA_BLACK;
int borderSize=1;
int borderColour=VGA_WHITE;
portal();
portal(UTFT* myDisplay);
void draw(void);
void drawContents(void);
private:
bool firstdraw=true;
};
class guage :public portal
{
public:
UTFT_Geometry* myGeometry;
float scaleMin=0.0;
float scaleMax=100.0;
float tick=20;
bool logScale=false;
int scaleColour=VGA_WHITE;
int foreColour=VGA_YELLOW;
float redBegin=80.0;
int redColour=VGA_RED;
float value=0;
float lastValue=0;
guage();
guage(UTFT*,UTFT_Geometry*);
void setNewValue(float);
};
class meter :public guage
{
public:
float startAngle=-40.0;
float endAngle=40.0;
float scaleRadius=80.0;
meter();
meter(UTFT*,UTFT_Geometry*);
void setValueAndDraw(float);
private:
void PointerDraw(float);
};
.cpp
#include "Arduino.h"
#include "UIelements.h"
portal::portal()
{
}
portal::portal(UTFT* UTFT)
{
// constructor: save the passed in method pointers for use in the class
myDisplay=UTFT;
}
void portal::draw(void)
{
// draw the contents
if (firstdraw)
{
// draw background and border
}
else
{
drawContents();
}
}
void portal::drawContents(void)
{
//portal class has no contents to draw, but subclasses will have..
}
...
meter::meter(UTFT* UTFT,UTFT_Geometry* Geometry)
{
// constructor save the passed in method pointers for use in the class
myDisplay=UTFT;
myGeometry=Geometry;
}
void meter::setValueAndDraw(float newValue)
{
setNewValue(newValue);
draw();
}
void meter::drawContents(void)
{
float xcentre=origin[1]+portalsize[1]/2;
float ycentre=origin[2]+portalSize[2]-1;
if (firstdraw=true)
//...more code in here..
}
错误信息
error: no 'void meter::drawContents()' member function declared in class 'meter'
我问过几个人,但每个人似乎都认为类继承看起来不错——这是 Arduino 的事,还是有什么我不明白的基本原理?任何帮助感激不尽。我担心它是 ;
等一些愚蠢的拼写错误或遗漏
最佳答案
在 C++ 中,当您想要覆盖子类中的行为时,您必须将函数标记为虚函数并再次在子类中声明它们。
所以你必须这样做:
class portal
{
public: virtual void drawContents();
};
void portal::drawContents()
{
//do stuff
}
class meter : public portal
{
public:
virtual void drawContents() override; // virtual may be omitted
};
void meter::drawContents()
{
// override behavior
}
drawContents 之后的关键字 override 是一个相对较新的 C++ 特性。它可能不会由 arduino 编译器实现。你可以省略它。
关于c++ - arduino c++ 中的继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43804222/