2013-12-13 72 views
-1
#include"iostream" 
using namespace std; 
class base{ 

public: 
void f() 
     { 
     cout<<"base f:"<<endl; // prints base f: 
     } 
}; 


int main() 
{ 
base *b; // even same out put with " base *b =NULL; " 

b->f(); 
return 0; 
} 

O/P:基F:函数调用++

任何一个可以请解释的函数是如何获取调用而不将对象分配到指针。

Thanks. 

回答

3

与未初始化(或初始化为0),指向对象成员函数的调用是不确定的行为,但也可以工作,因为没有尝试访问对象的变量,这里没有虚函数表。你可以看一下这个功能就像

void f_base(base* p) 
{ 
    cout << "base f:" << endl; 
} 

没有访问 - 没有错误,所有现代的编译器,将工作,但它可以随时改变。

0

这是无效的代码,但由于base :: f()中没有内容访问成员变量,因此没有无效的内存被触及。

如果您添加一个成员并尝试在函数中打印出来,您几乎肯定会崩溃。

0

您需要使用new

base *b; // even same out put with " base *b =NULL; " 

应该

base *b = new base; 

...需要一个delete以防止内存泄漏