search

Home  >  Q&A  >  body text

c++ - 一个面试题,求解答

#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()出错,求解答

高洛峰高洛峰2767 days ago510

reply all(5)I'll reply

  • PHP中文网

    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

    reply
    0
  • 黄舟

    黄舟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?

    reply
    0
  • 迷茫

    迷茫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. . . .

    reply
    0
  • 怪我咯

    怪我咯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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:40:32

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

    reply
    0
  • Cancelreply