2011-11-17 30 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。 –