简体   繁体   English

从C ++中的Abstract类继承

[英]Inheriting from Abstract Class in C++

#include <iostream>
#include <ostream>
using namespace std;

enum Month
{
    jan = 1,
    feb,
    mar
};

class Show
{
public:
    virtual void Display() = 0;
};

class Date : public Show
{
private:
    Month m;
    int day;
    int year;
public:
    Date( Month mName, int dayName, int yearName )
    {
        m = mName;
        day = dayName;
        year = yearName;
    }
    void Display()
    {
        cout << this->m << endl;
    }
};

void displayData( void *data[] )
{
    Month m = *( reinterpret_cast<const Month*> ( data[ 0 ] ) );
    cout << m << endl;
}

int main( int argc, char**argv )
{
    Date d1( jan, 28, 2017 );
    void * data[ 1 ];
    data[ 0 ] = &d1;
    displayData( data );
    return 0;
}

I'm getting the correct value for Month m in the function void displayData but when I inherit the Date class from the abstract class Show, then I'm getting a garbage value for Month m. 我在函数void displayData中获得了Month m的正确值,但是当我从抽象类Show继承Date类时,则得到了Month m的垃圾值。 Can anyone tell me why is this happening ? 谁能告诉我为什么会这样?

You are reinterpret-casting a Date as a Month . 您正在重新解释将DateMonth So, you are assuming that this is a safe conversion, but it isn't. 因此,您假设这是安全的转换,但事实并非如此。 It happens to work purely by accident when the Date class is just plain data, but when you derive the Date class from Show then the structure of the class becomes more complicated, and the accident does not hold true anymore. Date类只是纯数据时,它恰好偶然地起作用,但是当您从Show派生Date类时,该类的结构变得更加复杂,并且这种偶然性不再成立。

What is probably happening is that the first element in Date is now a pointer to the virtual method table of the class rather than the first member declared in the class. 可能发生的情况是Date中的第一个元素现在是指向该类的虚拟方法表的指针,而不是该类中声明的第一个成员。

You should not use the void pointer. 您不应该使用void指针。 Use a base class like Show instead, like: 使用类似Show的基类,例如:

void displayData( Show *data[] )
{
    data[0]->Display();
}

int main( int argc, char**argv )
{
    Date d1( jan, 28, 2017 );
    Show* data[ 1 ];
    data[ 0 ] = &d1;
    displayData( data );
    return 0;
}

Else how you would devide the void pointers to their classes? 否则,您将如何将void指针分配给它们的类?

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

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