#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;
}
我在函数 void displayData 中得到了 Month m 的正确值,但是当我从抽象类 Show 继承 Date 类时,我得到了 Month m 的垃圾值。谁能告诉我为什么会这样?
最佳答案
您正在将 Date
重新解释为 Month
。因此,您假设这是一个安全的转换,但事实并非如此。当 Date
类只是普通数据时,它的工作纯粹是偶然的,但是当您从 Show
派生 Date
类时,则结构类(class)变得更加复杂,事故不再成立。
可能发生的情况是 Date
中的第一个元素现在是指向类的虚方法表的指针,而不是类中声明的第一个成员。
关于c++ - 从 C++ 中的抽象类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44474051/