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?
PHP中文网2017-04-17 12:06:47
Because the size of A is half of B, the seta()
in data[1].a
actually becomes the main()
in data[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.
高洛峰2017-04-17 12:06:47
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
黄舟2017-04-17 12:06:47
The seta(A* data, int idx)
in function data[idx].a = 2
can be understood as *(long*)(data + idx*sizeof(A)) = 2;
, so there is a problem when you write it this way