C++中继承中遇到的构造函数问题
#include <iostream> class Base{ public: Base(){ } }; class Derive:public Base{ public: Derive(int a,int b){ } }; int main(){ Derive c(1,2); return 0; }
结果:编译通过,暂时不能说明问题。
#include <iostream> class Base{ public: Base(int a){ } }; class Derive:public Base{ public: Derive(int a,int b){ } }; int main(){ Derive c(1,2); return 0; }
结果:编译错误,错误信息:[Error] no matching function for call to ‘Base::Base()‘
#include <iostream> class Base{ public: Base(int a){ } }; class Derive:public Base{ public: Derive(int a,int b):Base(a){ } }; int main(){ Derive c(1,2); return 0; }
结果:编译成功
#include <iostream> class Base{ public: Base(int a){ } }; class Derive:public Base{ public: Derive(int a){ } }; int main(){ Derive c(1); return 0; }
结果:编译错误
#include <iostream> class Base{ public: Base(int a){ this->a = a; } Base(){ } public: int a; }; class Derive:public Base{ public: Derive(int a){ } }; int main(){ Derive c(1); std::cout << c.a << std::endl; return 0; }
结果:编译成功,运行输出结果为:3674912
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。