1#include <iostream> 2 3class cx { 4public: 5 virtual void func() { 6 std::cout << "func" << std::endl; 7 } 8 cx() { 9 func(); //构造函数中调用虚函数,语法上OK,效果上不对,因为当对象由子类进入基类构造时是基类类型的 10 //不管如何调用,总只能调用到基类的虚函数,无法调用到子类的虚函数,见下面测试 11 } 12 13}; 14 15class cb : public cx { 16 void func() { 17 std::cout << "cb.func" << std::endl; 18 } 19}; 20int main() 21{ 22 cx ox; //func 23 cb ob; //func 24 25 cx* pox = new cb(); //func 26 pox->func(); //cb.func 27}
C++构造函数调用虚函数的后果
Wesley13
2021-10-11
1420 0 0
点赞
收藏
评论区
加载中...