dynamic_cast
返回强制转换的指针,它不会修改参数本身。
您需要执行如下操作。
// removed the & since the elements are now pointers
GradStudent* gStudent = dynamic_cast<GradStudent*>(classRoom[1]);
cout << gStudent->getInfo();
警告 - 对于指针,如果它无法转换dynamic_cast
将返回nullptr
,您需要检查这一点以防止崩溃。
编辑:主要对象切片 http://en.wikipedia.org/wiki/Object_slicing你的代码中的错误 - #1 几乎是正确的
int arraySize = 3;
Student *classRoom;
classRoom = new Student[arraySize];
GradStudent gst1("Ta", "Da", 4444, 'A', "Death");
...
classRoom[0] = gst1;
应该
int arraySize = 3;
Student **classRoom;
// ^
classRoom = new Student*[arraySize];
// ^
GradStudent gst1("Ta", "Da", 4444, 'A', "Death");
classRoom[0] = &gst1;
// ^
Or just
Student* classRoom[3];
GradStudent gst1("Ta", "Da", 4444, 'A', "Death");
...
classRoom[0] = gst1;
如果没有这个,属于派生类的所有数据都会丢失,而仅存储基类数据,这称为对象切片.