在Arduino的继承code [英] Inheritance in Arduino Code
问题描述
我在写一些Arduino的code,并试图在某些类使用继承。我有一个类演员(我的基类)和类大理石(从演员继承)。下面是头文件:
I'm writing some Arduino code and attempting to use inheritance in some classes. I have a class "Actor" (my base class) and a class "Marble" (which inherits from Actor). Here are the header files:
Actor.h:
#ifndef Actor_h
#define Actor_h
#include "Arduino.h"
class Actor
{
public:
Actor();
void speak();
private:
};
#endif
Marble.h:
Marble.h:
#ifndef Marble_h
#define Marble_h
#include "Arduino.h"
#include "Actor.h"
class Marble : public Actor {
public:
Marble();
virtual void speak();
private:
};
#endif
Actor.cpp:
Actor.cpp:
#include "Arduino.h"
#include "Actor.h"
Actor::Actor()
{
}
void Actor::speak() {
Serial.println("Actor");
}
Marble.cpp:
Marble.cpp:
#include "Arduino.h"
#include "Marble.h"
void Marble::speak() {
Serial.println("Marble");
}
最后,循环功能我做的:
And finally, in the loop function I do:
void loop() {
Marble marble;
Actor children[2];
children[0] = marble;
children[0].speak();
这会导致演员被打印出来。
Which results in "Actor" being printed.
我发现这个漂亮的链接,这似乎类似于我的问题,但该决议似乎并没有为我工作:
http://arduino.cc/forum/index.php?topic=41884.0
I discovered this nice link which seems similar to my issue, but the resolution does not seem to work for me: http://arduino.cc/forum/index.php?topic=41884.0
所以。看来,当我创建我的演员的阵列和尝试,并坚持大理石在那里它被强制转换为演员,或者类似的东西等。但问题是,我有一些不同的角色,将全部由演员继承,我想他们的数组来遍历并呼吁它们覆盖的方法。
So. It seems like when I create my array of "Actors" and try and stick Marble in there it gets cast to an Actor, or something like that. Problem is, I'll have a few different characters that will all inherit from "Actor" and I'd like an array of them to iterate over and call overridden methods on them.
所以,也许这个问题是我如何处理这个问题,或者有一些语法错误?我不知道!
So, perhaps the problem is how I'm approaching this problem, or maybe there's some syntax errors? I don't know!
感谢您的帮助,
凯文
Thanks for your help, Kevin
推荐答案
您需要声明说话
为虚拟
在演员
类,不只是在大理石
类;如果没有,演员::说话
是的不的 - 虚拟功能,让你永远在preference调用到虚拟大理石::说话
。
You need to declare speak
as virtual
in the Actor
class, not just in the Marble
class; without that, Actor::speak
is a non-virtual function, so you will always be called in preference to the virtual Marble::speak
.
有关它的价值,这有什么好做的Arduino的:它只是一个单纯的C ++问题
For what it's worth, this has nothing to do with the Arduino: it's just a straight C++ issue.
这篇关于在Arduino的继承code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!