C++构造函数调用虚函数的后果

#include <iostream>

class cx {
public:
    virtual void func() {
        std::cout << "func" << std::endl;
    }
    cx() {
        func(); //构造函数中调用虚函数,语法上OK,效果上不对,因为当对象由子类进入基类构造时是基类类型的
        //不管如何调用,总只能调用到基类的虚函数,无法调用到子类的虚函数,见下面测试
    }

};

class cb : public cx {
    void func() {
        std::cout << "cb.func" << std::endl;
    }
};
int main()
{
    cx ox; //func
    cb ob; //func

    cx* pox = new cb(); //func
    pox->func(); //cb.func
}

猜你喜欢

转载自www.cnblogs.com/timeObjserver/p/12003563.html