Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.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++_Arrays_Virtual_Derived - Fatal编程技术网

C++ 从基类数组调用派生函数

C++ 从基类数组调用派生函数,c++,arrays,virtual,derived,C++,Arrays,Virtual,Derived,如何从基类数组调用派生函数 例: #包括 #包括 甲级{ 公众: 虚空prnt(){ 正如Justin所评论的,您正在目睹一个案例。获得您期望的行为的一种方法是使用指针: int main() { a* array[3]; array[0] = new a(); array[1] = new b(); array[2] = new a(); array[1]->prnt(); // Don't forget to delete them!

如何从基类数组调用派生函数

例:

#包括
#包括
甲级{
公众:
虚空prnt(){

正如Justin所评论的,您正在目睹一个案例。获得您期望的行为的一种方法是使用指针:

int main() {
    a* array[3];
    array[0] = new a();
    array[1] = new b();
    array[2] = new a();

    array[1]->prnt();

    // Don't forget to delete them!
    for (int i = 0; i < 3; ++i) {
        delete array[i];
    }
}
intmain(){
a*数组[3];
数组[0]=新的a();
数组[1]=新的b();
数组[2]=新的a();
数组[1]->prnt();
//别忘了删除它们!
对于(int i=0;i<3;++i){
删除数组[i];
}
}
上面是对象切片。请阅读

多态性仅适用于指针和引用

 a *array[3];
 array[0] = new a();
 array[1] = new b();
 array[2] = new a();

 array[1]->print() 

无论如何都有办法解决这个问题。如何解决它?
b
对于这个代码来说不是一个可能的输出。你是说
a
?是的。a就是我的意思。抱歉,时间太晚了。你不能,因为它是基类的数组,这意味着其中的对象属于基类,而不是派生类,所以你不能对它调用派生类函数它不是派生类。
 array[1] = b();
 a *array[3];
 array[0] = new a();
 array[1] = new b();
 array[2] = new a();

 array[1]->print()