c++ - 一个面试题,求解答
高洛峰
高洛峰 2017-04-17 11:38:32
0
5
512
#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()出错,求解答

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(5)
Ty80

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

黄舟

There 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.

Peter_Zhu

Everyone has said very well.
I'll add a picture.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template