简体   繁体   English

在子类的子类中使用基类C ++的虚拟方法

[英]use virtual method of base class C++ in child of child class

I've created a class named 'Device' which get inherited by multiple devices (for example, RFDevice, AccelleroDevice) 我创建了一个名为“设备”的类,该类被多个设备(例如,RFDevice,AccelleroDevice)继承

The Device class inherited a Thread class. Device类继承了Thread类。 This Threadclass includes a Pure virtual function named run. 此Threadclass包含一个名为run的Pure虚拟函数。 Is it possible to accesss this pure virtual function in RFDevice or AcelleroDevice. 是否可以在RFDevice或AcelleroDevice中访问此纯虚拟功能。

So, 所以,

ThreadClass->DeviceClass->RFDeviceClass. ThreadClass-> DeviceClass-> RFDeviceClass。

I've tried to add 我尝试添加

' virtual void run(void) = 0' also in the device class but this wont work. 设备类中的'virtual void run(void)= 0'也不起作用。

Greets, 问候,

Only if the virtual function is not private. 仅当虚拟功能不是私有的时。 If it is, then you cannot call it and are not supposed to, either: 如果是,那么您将无法调用它,也不应调用它:

class ThreadClass
{
public:
    virtual ~ThreadClass() {}
private:
    virtual void run() = 0;
};

class Device : public ThreadClass
{
};

class RFDevice : public Device
{
public:
    void f()
    {
        run(); // compiler error
    }
};

If it is protected or public, then it will work, provided there is an implementation of the function somewhere down the class hierarchy. 如果它是受保护的或公共的,那么它将起作用,只要该函数在类层次结构中的某个地方实现。 But with the exception of the destructor, virtual functions should rarely be public or protected in C++: 但是,除了析构函数外,虚函数应该很少在C ++中公开或受保护:

class ThreadClass
{
public:
    virtual ~ThreadClass() {}
protected:
    virtual void run() = 0; // non-private virtual, strange
};

class Device : public ThreadClass
{
};

class RFDevice : public Device
{
protected:
    virtual void run()
    {
    }

public:

    void f()
    {
        run(); // works
    }
};

Of course, this does not technically call the base function. 当然,这在技术上并不称为基本函数。 And that's a good thing; 那是一件好事; you'd end up with a pure virtual function call otherwise, and your program would crash. 否则,您将获得纯虚拟函数调用,并且程序将崩溃。

Perhaps what you need to do is to just implement the private virtual function. 也许您需要做的只是实现私有虚拟功能。 That would be the preferred class design: 那将是首选的类设计:

class ThreadClass
{
public:
    virtual ~ThreadClass() {}
    void execute()
    {
        run();
    }
private:
    virtual void run() = 0;
};

class Device : public ThreadClass
{
};

class RFDevice : public Device
{
private:
    virtual void run()
    {
    }
};

int main()
{
    RFDevice d;
    d.execute();
}

If you are not just maintaining a legacy code base, you should probably get rid of your thread class and use C++11 multi-threading . 如果您不只是维护旧版代码库,则可能应该摆脱线程类并使用C ++ 11 multi-threading

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM