1

although we are printing bval, output is showing value of dval as well. Whats actual logic does compiler using? My expected output was 00000 00000, but I m getting output as 00000 01010.

#include <iostream>
using namespace std;

class base {
 public:
   int bval;
   base() { bval = 0; }
};

class deri : public base {
  public:
    int dval;
    deri() { dval = 1; }
 };

 void SomeFunc(base *arr , int size) {
   for(int i = 0; i < size; i++, arr++)
     cout << arr-> bval;
   cout<<endl;
 }

 int main() {
   base BaseArr[5];
   SomeFunc(BaseArr, 5);
   deri DeriArr[5];
   SomeFunc(DeriArr, 5);
   return 0;
 }
4

1 回答 1

3

你在欺骗系统,并得到“切片”。

由于deri大于base,当你这样做时arr++,指针只会base向前推进一个对象。

解决方案是有一个指针数组,并传递 a base **arr,如下所示:

base *foo[5];
base BaseArr[5];
SomeFunc(BaseArr,5);
for(int i = 0; i < 5; i++)
{ 
   foo[i] = &BaseArr[i];
}
SomeFunc(foo, 5);
于 2013-04-24T10:47:35.940 回答