C++中虚表指针的存放位置
2013-07-27 14:03
225 查看
以前一直以为C++为了兼容C而把虚函数表指针Vptr放在了对象末尾,而且在《inside the C++ object model》里面也是这么描述的。但是我错了,今天愕然发现不是这样的。而且无论是在g++编译器还是在ms的编译器上都不是这样的!
#include <iostream>
#include <cstdlib>
using namespace std;
#ifndef BYTE
#define BYTE char
#endif
#define myMain main
class A{
private:
int _a;
int _b;
public:
A(int a=0,int b=0):_a(a),_b(b){}
virtual ~A(){cout<<"A destructor"<<endl;}
friend ostream &operator<<(ostream& out , const A &a){out<<a._a;return out;}
};
class B : public A{
private:
int b;
public:
virtual ~B(){cout<<"B destructor"<<endl;}
};
int myMain(int argc , char *argv[])
{
A a(12,13);
cout<<a<<endl;
int *b=reinterpret_cast<int*>(&a);
cout<<*b<<endl;
b++;
cout<<*b<<endl;
b++;
cout<<*b<<endl;
system("pause");
return EXIT_SUCCESS;
}
程序的输出为:
12
4463692
12
13
显然上面的为虚表指针的值,下面为成员变量的值,这说明C++中虚表指针是放在对象的开头的!!!
#include <iostream>
#include <cstdlib>
using namespace std;
#ifndef BYTE
#define BYTE char
#endif
#define myMain main
class A{
private:
int _a;
int _b;
public:
A(int a=0,int b=0):_a(a),_b(b){}
virtual ~A(){cout<<"A destructor"<<endl;}
friend ostream &operator<<(ostream& out , const A &a){out<<a._a;return out;}
};
class B : public A{
private:
int b;
public:
virtual ~B(){cout<<"B destructor"<<endl;}
};
int myMain(int argc , char *argv[])
{
A a(12,13);
cout<<a<<endl;
int *b=reinterpret_cast<int*>(&a);
cout<<*b<<endl;
b++;
cout<<*b<<endl;
b++;
cout<<*b<<endl;
system("pause");
return EXIT_SUCCESS;
}
程序的输出为:
12
4463692
12
13
显然上面的为虚表指针的值,下面为成员变量的值,这说明C++中虚表指针是放在对象的开头的!!!
相关文章推荐
- c++中使用基类指针Vector 存放子类对象(0xcccccccc 处未处理的异常: 0xC0000005: 读取位置 0xcccccccc 时发生访问冲突 )
- C++指向虚函数表指针存放位置
- C++中this指针存放在哪里
- 关于C++中虚函数表存放位置的思考
- c++指针复制指向同一个位置问题
- 关于C++中虚函数表存放位置的思考
- 常考的开发笔试题 c++里有关指针的内容中,const的位置对指针含义的影响?
- C/C++——C风格的字符串的指针指向的内存位置问题(易错)
- C++中的引用变量在内存中存放的位置
- <C/C++>指向指针的指针、指向数组的指针以及存放指针的数组
- 关于C++中虚函数表存放位置的思考
- C++中的引用变量在内存中存放的位置
- 【C/C++】如何利用char型数组buffer存放指针
- C++中虚函数表存放位置
- 你好,C++(15)四两拨千斤——3.9 指向内存位置的指针
- c++ vector中存放指针
- thiscall仅仅应用于“C++”成员函数(this指针存放于CX寄存器,参数从右到左压)
- C语言_为什么字符串可以赋值给字符指针变量,字符串的属性及存放位置
- 关于C++中虚函数表存放位置的思考
- c++的代码、变量在内存中的存放位置