所有带virtual的类的对象,里面最上面有一个隐藏的指针vptr,指向一张表vtable
1 #include <iostream> 2 using namespace std; 3 4 class A 5 { 6 public: 7 A() :i(10) {} 8 virtual void f() { std::cout << "A::f()" << std::endl; } 9 int i; 10 }; 11 12 void main() 13 { 14 A a, b; 15 a.f(); 16 17 std::cout << sizeof(a) << std::endl;//8,不是4 18 19 int *p = (int *)&a; 20 int *q = (int *)&b; 21 22 int *x = (int *)*p; 23 24 std::cout << *x << std::endl; 25 26 std::cout << *p << " " << *q << std::endl;//一样 27 28 system("pause"); 29 }
1234
时间: 2024-10-12 12:53:08