请判断如下代码是否有问题:

    1. //给出实例
    2. class animal {
    3. public:
    4. void sleep() { cout << "animal sleep" << endl; }
    5. void breathe() { cout << "animal breathe haha" << endl; }
    6. };
    7. class fish : public animal {
    8. public:
    9. void breathe(){ cout << "fish bubble" << endl; }
    10. };
    11. int main() {
    12. animal *pAn=nullptr;
    13. pAn->breathe(); // output: ?
    14. fish *pFish = nullptr;
    15. pFish->breathe(); // output: ?
    16. return 0;
    17. }

    答: 没有问题,输出如下: :::info animal breathe haha
    fish bubble :::

    解释:
    因为在编译时对象就绑定了函数地址,和指针空不空没关系。pAn->breathe();编译的时候,函数的地址就和指针pAn绑定了;调用breath(*this), this就等于pAn。由于函数中没有需要解引用this的地方,所以函数运行不会出错;

    但是若用到this,因为this=nullptr,运行出错。例如我们在成员函数中需要访问成员变量就会报错。