[C++] vptr, where are you?

Search(c++在线运行)

C++
sizeof(C1)=16 sizeof(C1*)=8
h 20 @ 00 00 00 00 00 C + + 00 _ _ _ _ _ _ _ _ P 20 @ 00 00 00 00 00 C P P 00 _ _ _ _ _ _ _ _ P 20 @ 00 00 00 00 00 C X X 00 _ _ _ _ _ _ _ _ _ _ _ _
XXX

#include <string.h>
#include <stdio.h>
#include <new>
typedef unsigned char    byte;
struct C1 {
    char m_str[5];
    C1(const char* s) { strcpy(m_str, s); }
    virtual void print() { puts(m_str); }
};
struct C2 : public C1 {
    C2(const char* s) : C1(s) {}
    virtual void print() { puts(m_str); }
};
int main() {
    enum { N = 64 };
    byte    buf[N];
    memset(buf, '_', N);
    C1    *p = new(buf)C1("C++"), *q = new(buf + 20)C2("CPP");
    C2    *r = new(buf + 40)C2("CXX");
    p->print();printf("sizeof(C1)=%d sizeof(C1*)=%d\n", sizeof(C1), sizeof(C1*));
    for (byte* p = buf; p < buf + N; p++) {
        const byte    b = *p;
        if (b > 32) printf("%c ", b); else printf("%02x ", b);
    }
    puts("");
    if (byte *pb = (byte*)memmem(buf, N, "CXX", 3)) (*pb = 'X'), r->print();
    return 0;
}

 

上一篇:leetcode:两个数组的交集(双指针)


下一篇:sizeof的概念