Why!!!!!!!!!!I don't think it can run!
我在编程时遇到一个非常费解的问题。
我认为基类指针(b++)->i会出现如(b+i)->i的东东,竟然是很规矩的0
以为base还自己留了个的数据块。结果运行derives[i].Base::i。发现没有。
现在我非常想知道(b++)->i的0是怎么来的。大虾救命呀。我刚从java过来。不懂呀!
#include <iostream>
using namespace std;
class Base{
public: int i;
};
class Derived:public Base{
public :int n;
Base b[10];
};
int main()
{
Derived derives[5];
Derived *derive;
derive=derives;
for(int i=0;i<5;i++)
{
derives[i].i=i;
}
Base *b;
b=derives;
//b++;
// b++;
cout<<"\n*b:(b++)->i:";
for(int i=0;i<5;i++)
{
cout<<" "<<(b++)->i;
}
cout<<"\n derives[i] : \n";
for(int i=0;i<5;i++)
{
cout<<" "<<derives[i].i;
}
cout<<"\n Other writing method : (b+i)->i\n";
for(int i=0;i<5;i++)
{
cout<<" "<<(b+i)->i;
}
cout<<"\n output derived : (derive+i)->i\n";
for(int i=0;i<5;i++)
{
cout<<" "<<(derive+i)->i;
}
cout<<"\n output derived : (derive++)->i\n";
for(int i=0;i<5;i++)
{
cout<<" "<<(derive++)->i;
}
cout<<"\n Some doubt, Why b++->i output is 0?Then the derives[i].base::i?:\n";
for(int i=0;i<5;i++)
{
cout<<" "<<derives[i].Base::i;
}
// cout<<b->i;
cout<<"\n";
return 0;
}
输出:
*b:(b++)->i: 0 0 0 0 0
derives[i] :
0 1 2 3 4
Other writing method : (b+i)->i
0 -12615240 -12845056 -12845056 -1
output derived : (derive+i)->i
0 1 2 3 4
output derived : (derive++)->i
0 1 2 3 4
Some doubt, Why b++->i output is 0?Then the derives[i].base::i?:
0 1 2 3 4