关于c++的构造函数的几个说明
分类:C++, Others
阅读 (1,075)
Add comments
1月 172017
本文为了说明基类和派生类的构造函数的声明和使用,主要是以下几点:
- 派生类所有构造函数都会默认调用基本的默认构造函数(没有参数的构造函数,如Base())
- 派生类如果想显示的调用基类的带参数的构造函数,要在派生类的初始化器处调用,而不能在构造函数的实现里调用(即不能在花括号里调用{})
示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#include <iostream> class Shape{ public: int length = 0; public: Shape(){ length = 3; //子类的所有构造函数都会调用基类的默认构造函数 } Shape(int len){ length = len; } }; class Circle: public Shape{ public: Circle() {}; }; class Square: public Shape{ public: Square(int len) : Shape(len){ //在初始化器这里调用基类的相关构造函数,而不是在下面的实现里 // Shape(len); //在这里会报错,放在, redefinition of 'len' with a different type: 'Shape' vs 'int' } Square(std::string name){}; //这个构造函数会调用Shape的默认构造函数 }; int main(int argc, char **argv) { Shape shape ; std::cout << "Shape length: " << shape.length << std::endl; Circle circle; std::cout << "Circle length: " << circle.length << std::endl; Square square(10); std::cout << "Square length: " << square.length << std::endl; Square mysquare("mysquare"); std::cout << "mysquare length: " << mysquare.length << std::endl; } |
输出结果如下:
1 2 3 4 |
Shape length: 3 Circle length: 3 Square length: 10 mysquare length: 3 |