Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么不调用子类的虚拟函数_C++_Arduino - Fatal编程技术网

C++ 为什么不调用子类的虚拟函数

C++ 为什么不调用子类的虚拟函数,c++,arduino,C++,Arduino,我有一个基类和一个派生类: plugin.h #ifndef PLUGIN_H #define PLUGIN_H // plugin states #define PLUGIN_IDLE 0 class Plugin { public: Plugin(); ~Plugin(); virtual void loop(); }; #endif plugin.cpp #include <Arduino.h> #include "plugin.h" Plugin::P

我有一个基类和一个派生类:

plugin.h

#ifndef PLUGIN_H
#define PLUGIN_H

// plugin states
#define PLUGIN_IDLE 0

class Plugin {
public:
  Plugin();
  ~Plugin();

  virtual void loop();
};

#endif
plugin.cpp

#include <Arduino.h>
#include "plugin.h"

Plugin::Plugin() {
}

Plugin::~Plugin(){
}

void Plugin::loop(){
  Serial.println("Plugin::loop()");
}
我希望调用派生实例的
loop()
方法将执行
OneWirePlugin::loop()

但是,只有在派生类上下文中调用它时才会发生这种情况:

Plugin p = Plugin();
Plugin o = OneWirePlugin(ONEWIRE_PIN);
OneWirePlugin q = OneWirePlugin(ONEWIRE_PIN);
p.loop(); // Plugin::loop()
o.loop(); // Plugin::loop()
q.loop(); // OneWirePlugin::loop()

我的虚拟方法允许调用派生实现,特别是通过
*插件
指针引用时,有什么问题吗?

循环
必须声明为
虚拟

class Plugin {

// ...

virtual void loop();
此外,要使多态性发挥作用,您需要一个指针或引用:

Plugin* o = new OneWirePlugin(ONEWIRE_PIN);
o->loop();

// ...

delete o;
(在代码中,发生,如注释部分中所述)

然后考虑使用智能指针(如<代码> UnQuyPPTR <代码>或<代码> SydDypPTR < /代码>)。


如果您使用的是C++11,您还应该在子类中用
重写
说明符标记
循环

class OneWirePlugin : public Plugin {

// ...

void loop() override { 
在你的问题中— 1.Plugin p=新插件(); 2.插件o=OneWirePlugin(ONEWIRE_引脚)

  • 将调用Plugin::loop()作为它的基类对象
  • 在创建插件对象时,还将调用Plugin::loop(),通过这种方式进行对象切片,从派生类对象形成基类对象
  • 下面的例子会有所帮助

    class Base { int x, y; };
    
    class Derived : public Base { int z, w; };
    
    int main() 
    {
        Derived d;
        Base b = d; // Object Slicing,  z and w of d are sliced off
    }
    
    在IDE上运行
    将派生类对象指定给基类对象时会发生对象切片,派生类对象的附加属性被分割成基类对象。

    在<代码>插件< /COD>中声明没有<代码>虚拟< /代码>函数,也要注意,你可能需要实现C++不是java。对所有1个选民:我已经提到过我也用虚拟技术测试过,这是因为TI切片没有帮助。因此,如果阅读负担太重,请停止阅读……我更新了问题,以强调切片是问题的根源。
    make_unique
    并不比
    new
    @SergeyA稍微好一点,因为您不需要
    delete
    。您能详细说明一下吗?“我不明白这一点。”谢尔盖亚详细说明了什么?也许我误解了你的评论。@而且C++11之前的代码至少有
    std::auto_ptr
    。它仍然比使用原始指针要好。
    class Base { int x, y; };
    
    class Derived : public Base { int z, w; };
    
    int main() 
    {
        Derived d;
        Base b = d; // Object Slicing,  z and w of d are sliced off
    }