Arduino 代码中的继承 [英] Inheritance in Arduino Code

查看:25
本文介绍了Arduino 代码中的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些 Arduino 代码并尝试在某些类中使用继承.我有一个Actor"类(我的基类)和一个Marble"类(继承自 Actor).以下是头文件:

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

大理石.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:

#include "Arduino.h"
#include "Actor.h"

Actor::Actor()
{
}

void Actor::speak() {
  Serial.println("Actor"); 
}

大理石.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();

这会导致打印演员".

我发现了这个不错的链接,它似乎与我的问题相似,但该解决方案似乎对我不起作用: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

所以.似乎当我创建我的演员"数组并尝试将 Marble 粘贴在其中时,它会被投射到演员上,或者类似的东西.问题是,我将有几个不同的字符,它们都将继承自Actor",我想要一个数组来迭代并调用它们的重写方法.

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!

感谢您的帮助,凯文

推荐答案

你需要在Actor类中声明speakvirtual,不仅仅是在 Marble 类中;没有那个,Actor::speak 是一个 -虚拟函数,所以你总是会优先于虚拟 Marble::speak 被调用.

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 代码中的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆