#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()出错,求解答
When calling a member function, the this pointer will be passed in as a parameter.
f1()
The body of the function is stillcout<<"f1"<<endl;
, so there will be no problem. The body of thef2()
function is actuallycout<<this->i<<endl;
, and the this pointer is NULL, so an error will occurThere is no declared object. If the private member variable address has an offset, it will point to an unknown address, right?
Is it because the object is not instantiated, so the constructor is not called, and there is nothing in i? Equal answer. . . .
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.
Everyone has said very well.
I'll add a picture.