我寫了一些測試代碼,找出有關成員函數的地址。但結果讓我困惑。代碼是指針到成員函數的地址是什麼,沒有虛擬也沒有繼承
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
class A
{
public:
A(char _a, char _b, char _c, char _t):a(_a), b(_b), c(_c), t(_t){}
private:
char t;
char a;
public:
char b;
char c;
void test1(){std::cout << a << std::endl;}
void test2(){std::cout << b << std::endl;}
void test3(){std::cout << c << std::endl;}
void test4(){std::cout << t << std::endl;}
static void print(){
char A::*pa = &A::a;
char A::*pb = &A::b;
char A::*pc = &A::c;
char A::*pt = &A::t;
printf("data member : %p, %p, %p, %p\n", pa, pb, pc, pt);
void (A::*pf1)() = &A::test3;
void (A::*pf2)() = &A::test2;
void (A::*pf3)() = &A::test3;
void (A::*pf4)() = &A::test2;
printf("function member : %p, %p, %p, %p\n", pf1, pf2, pf3, pf4);
}
};
int main()
{
A::print();
//system("pause");//need on Dev-c++
return 0;
}
我運行ubuntu上與g ++以及WINDOS與開發 - C++此代碼,結果是相同的
data member : 0x1, 0x2, 0x3, (nil)
function member : 0x8048780, (nil), 0x804874e, (nil)
爲什麼PF2和PF4是nil?
你使用編譯器優化嗎? – klm123 2012-08-10 02:48:30
[指向成員函數是非常奇怪的動物](http://blogs.msdn.com/b/oldnewthing/archive/2004/02/09/70002.aspx)。 – 2012-08-10 02:57:19