之前看C++特性,不知所然,今天得空回顾以下,似有所或。
参考B站视频和RUNOOB,码字记录。
子类可以自动继承父类方法(public)和属性(private),包括构造函数(无参数的构造函数)。父类中private更改为protected,主函数不能访问,但是派生类能访问。
#include <iostream> using namespace std; class Box { public: double get_volume(void); void set(double l, double b, double h); Box(); //无参数的构造函数 Box(double a, double b, double c); //可以更改变量的构造函数,重构函数 protected: double length; // 长度 double breadth; // 宽度 double height; // 高度 }; Box::Box() { length = 0.0; breadth = 0.0; height = 0.0; } double Box::get_volume(void) { return length * breadth * height; } void Box::set(double len, double bre, double hei) { length = len; breadth = bre; height = hei; } ///Box_wood(木箱子类)来自box类公有(方法)派生 // class Box_wood: public Box{ // } class Box_wood : public Box { public: Box_wood(); Box_wood(double l, double w, double h, string m); double Box_wood_get_weight(); void Box_wood_set(double len, double wit, double hei, string mat); private: /* data */ string materia; }; Box_wood::Box_wood() { Box(); materia = "wood"; } Box_wood::Box_wood(double l, double w, double h, string m) //有写法,加上:Box(double l,double h) { //这里不能定义 height =h; //子类能继承,但是不能使用构造函数修改父类已经构造的属性??? //构造即为初始化,对父类属性初始化,2次没有必要 length = l; height = h; height = h; materia = m; } void Box_wood::Box_wood_set(double len, double wit, double hei, string mat) { set(len, wit, hei); materia = mat; } double Box_wood::Box_wood_get_weight() { double density(0.0); double volume(0.0); if (materia == "wood") { /* code */ density = 0.9; } else { density = 0; } volume = get_volume(); return density * volume; } int main() { Box father_box; cout << "结果输入如下:" << endl; cout << "father_box的构造体积" << father_box.get_volume() << endl; father_box.set(1.1, 1.2, 3.2); cout << "father_box的设置体积" << father_box.get_volume() << endl; Box_wood a; cout << "子类a的构造体积" << a.get_volume() << endl; double weight_1(0.0); a.Box_wood_set(4.0, 5.0, 5.0, "wood"); // a.set(16.0, 8.0, 12.0); //不能cout箱子的长宽高,即私有成员变量在main函数中看不到. weight_1 = a.Box_wood_get_weight(); cout << "a 的重量:" << weight_1 << endl; return 0; }