C++編譯器對虛函數和普通成員函數的處理方式

來源:互聯網
上載者:User

//現在的疑問是:既然虛函數表的訪問指標已經被破壞,那怎麼又會調到虛的解構函式呢。

#include <iostream>
using namespace std;

class CPoint {
public:
  int m_ix;
  int m_iy;
  CPoint(const int p_ix = 0, const int p_iy = 0) : 
    m_ix(p_ix), m_iy(p_iy) {
  }
  int getX() const {
    return m_ix;
  }
  int getY() const {
    return m_iy;
  }
  virtual ~CPoint() { cout<<"調用解構函式"<<endl; }
  virtual void fun(){
   cout<<"調用fun()"<<endl;
  }
};

int main() {
  CPoint *pa;
  CPoint objPoint(5, 10);
  pa=&objPoint;
  int* pInt = (int*)&objPoint;
  *(pInt+0) = 100; // 企圖改變x的值
  *(pInt+1) = 200; // 企圖改變y的值

  cout << "X = " << objPoint.getX() << endl;
  cout << "Y = " << objPoint.getY() << endl;
  objPoint.fun();      //注意這一行和下面一樣的區別,這就證明了無論是否是虛函數,編譯器都會為其編譯出CPoint@@fun()這種形式函數,但是pa->fun()這種文法形式,編譯器會按照虛表的方式訪問
  pa->fun();            //因為虛函數表已經地址已經被破壞,所以無法訪問虛函數

  return 0;      //在主函數退出時出現了調用解構函式,說明訪問虛構函數的方式為成員函數調用,而非虛函數表方式調用
}

/*
第一個是注掉pa->fun()這行
[student@SEP4020 objectmemery]$ ./a.out 
X = 200
Y = 10
調用fun()
調用解構函式

 

[student@SEP4020 objectmemery]$ vim objectmemery.cpp 
[student@SEP4020 objectmemery]$ g++ objectmemery.cpp 
[student@SEP4020 objectmemery]$ ./a.out 
X = 200
Y = 10
調用fun()
段錯誤

*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.