class A{
public:
long a;
};
class B : public A {
public:
long b;
};
void seta(A* data, int idx) {
data[idx].a = 2;
}
int main(int argc, char *argv[]) {
B data[4];
for(int i=0; i<4; ++i){
data[i].a = 1;
data[i].b = 1;
seta(data, i);
}
for(int i=0; i<4; ++i){
std::cout << data[i].a << data[i].b;
}
return 0;
}
请问输出为什么是22221111?
Because the size of A is half of B, the
seta()
indata[1].a
actually becomes themain()
indata[0].b
. This is a problem of C++ memory arrangement.But in fact, when you write the program this way, you assign object B to object A, instead of assigning the pointer to object B to the pointer to object A. This way of writing is inherently wrong.
If such a problem occurs, you can first use single-step debugging to see how each step is executed, and then try to analyze it yourself based on the phenomenon during single-step debugging
The
seta(A* data, int idx)
in functiondata[idx].a = 2
can be understood as*(long*)(data + idx*sizeof(A)) = 2;
, so there is a problem when you write it this way