#include <iostream>
using namespace std;
class Myclass
{
public:
Myclass():i(0){};
void f1(){cout<<"f1"<<endl;}
void f2(){cout<<i<<endl;}
private:
int i;
};
int main()
{
Myclass *p = NULL;
// f1
p->f1();
// error
p->f2();
return 0;
}
如注释所说,p->f2()出错,求解答
PHP中文网2017-04-17 11:40:32
When calling a member function, the this pointer will be passed in as a parameter. f1()
The body of the function is still cout<<"f1"<<endl;
, so there will be no problem. The body of the f2()
function is actually cout<<this->i<<endl;
, and the this pointer is NULL, so an error will occur
黄舟2017-04-17 11:40:32
There is no declared object. If the private member variable address has an offset, it will point to an unknown address, right?
迷茫2017-04-17 11:40:32
Is it because the object is not instantiated, so the constructor is not called, and there is nothing in i? Equal answer. . . .
怪我咯2017-04-17 11:40:32
Myclass *p, p only has the class address access capability of Myclass, but does not allocate its own data heap. Calling f1 only accesses the function of the class, but the variable i is accessed during the execution of f2, which does not exist. , because the data heap of p does not exist, so an error will occur. The same as above, this is empty.