WEB开发网
开发学院软件开发VC ATL布幔之下的秘密(2) 阅读

ATL布幔之下的秘密(2)

 2006-07-22 22:55:03 来源:WEB开发网   
核心提示: 程序22.#include <iostream>using namespace std;class Base {public:Base() {cout << "In Base" << endl;cout << "

程序22.#include <iostream>
using namespace std;
class Base {
public:
  Base() {
    cout << "In Base" << endl;
    cout << "This Pointer = " << (int*)this << endl;
    cout << endl;
  }
virtual void f() { cout << "Base::f" << endl; }
};
class Drive : public Base {
public:
  Drive() {
    cout << "In Drive" << endl;
    cout << "This Pointer = " << (int*)this << endl;
    cout << endl;
  }
virtual void f() { cout << "Drive::f" << endl; }
};
int main() {
  Drive d;
  cout << "In Main" << endl;
  cout << (int*)&d << endl;
  return 0;
}
程序的输出为: In Base
This Pointer = 0012FF7C
In Drive
This Pointer = 0012FF7C
In Main
0012FF7C
这就表示,整个内存位置中,只有一个对象的存在。那么就让我们把这个指针指向的值打印出来,也就是虚函数表的指针vptr指向的值,VTable的地址。

程序23. #include <iostream>
using namespace std;
class Base {
public:
  Base() {
    cout << "In Base" << endl;
    cout << "Virtual Pointer = " << (int*)this << endl;
    cout << "Address of Vtable = " << (int*)*(int*)this << endl;
    cout << "Value at Vtable = " << (int*)*(int*)*(int*)this << endl;
    cout << endl;
  }
  virtual void f1() { cout << "Base::f1" << endl; }
};
class Drive : public Base {
public:
  Drive() {
    cout << "In Drive" << endl;
    cout << "Virtual Pointer = " << (int*)this << endl;
    cout << "Address of Vtable = " << (int*)*(int*)this << endl;
    cout << "Value at Vtable = " << (int*)*(int*)*(int*)this << endl;
    cout << endl;
  }
  virtual void f1() { cout << "Drive::f2" << endl; }
};
int main() {
  Drive d;
  return 0;
}
程序的输出为:In Base
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C08C
Value at Vtable = 004010F0
In Drive
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C07C
Value at Vtable = 00401217
这个程序示范了基类和派生类中不同的虚函数表地址。为了更好地弄懂这一问题,那就让我们把继承层次加深,并添加一个继承于Drive类的MostDrive类,然后构建一个它的对象。

上一页  1 2 3 4 5 6 7  下一页

Tags:ATL 之下 秘密

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接