2011-11-17 25 views
0
#include <iostream> 

class Test { 
public: 
    int i; 
    void print() 
    { 
     std::cout << "Hello" << std::endl; 
    } 
}; 

int main() 
{ 
    class Test *p = NULL; 
    p->print(); 
    (*p).print(); 
} 

Output: 

Hello 
Hello 

我的理解是對象的方法和成員變量都存儲在不同的內存位置,但是當p被指定爲NULL如何能夠解決調用Test::print()C++概念Acessing公共方法

Test6:~ 1001> g++ --version 
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46) 
Copyright (C) 2006 Free Software Foundation, Inc. 
This is free software; see the source for copying conditions. There is NO 
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 

Test6:~ 1002> g++ manoj.cpp 
Test6:~ 1003> ./a.out 
Hello 
Hello 
Test6:~ 1004> cat manoj.cpp 
#include <iostream> 

class Test { 
public: 
int i; 
void print() 
{ 
std::cout << "Hello" << std::endl; 
} 
}; 

int main() 
{ 
class Test *p = NULL; 
p->print(); 
(*p).print(); 
} 
Test6:~ 1005> 
+2

我猜想這是未定義的行爲,而且你很幸運它的工作。 [主叫通過NULL類指針類方法]的 –

+0

可能重複(http://stackoverflow.com/questions/2505328/calling-class-method-through-null-class-pointer) –

回答

3

除非一個類具有虛函數(即編譯器不創建vtable),否則所有指向這些方法的指針都將在程序中硬編碼,因此不需要使用任何可變信息。但是,即使在這種情況下,它也不會有有效的指針this,所以它仍會崩潰。

+0

就像調用一個函數'空隙打印( class Test *)'。雖然arg'class Test *'沒有初始化,但它仍然可以工作,因爲函數內容與arg無關。 –

0

你根本無法做到這一點。 此代碼不會編譯 ,並且您無法尋址空指針。嘗試使用:

int main() 
{ 
    // no need for 'class' keyword when declaring the pointer: 
    Test* p = new Test(); // use default constructor provided by compiler 
    p->print(); 
    (*p).print(); 
    // you also need to delete the pointer before returning, but that's irrelevant 
    return 0; // you need this too 
} 
+0

爲什麼不編譯它? –

+0

@SethCarnegie,沒有'main()'返回'和main()'裏面的'class'關鍵字。你讓我懷疑我的C++知識。 :P – Zeenobit

+0

除非我錯了(我通常是這樣),那麼在類名前面使用'class'就好了,就像他們以前用C中的struct一樣。另外,如果你不' t從'main'返回一個值,顯然[編譯並運行良好的gcc](http://ideone.com/CIVd3),哪一個可能會令人不安。但無論如何+1。 –