c++ 类的输出问题
PHPz
PHPz 2017-04-17 12:04:47
0
3
542
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?

PHPz
PHPz

学习是最好的投资!

reply all(3)
洪涛

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.

小葫芦

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 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template