C++程序设计chapter4继承与派生

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

class CRectangle: public CPolygon {
public: int area () { return (width * height); }
};
class CTriangle: public CPolygon {
public: int area () { return (width * height / 2); }
// constructors and derived classes #include <iostream> using namespace std; class mother {
public: mother () { cout << "mother: no parameters\n"; } mother (int a) { cout << "mother: int parameter\n"; }
};
int main () {
daughter Alice; son Tom; return 0; }
Result:
mother: no parameters daughter: int parameter
mother: int parameter son: int parameter
};
class daughter : public mother {
public: daughter (int a) { cout << "daughter: int parameter\n\n"; }
}; class son : public mother {
public: son (int a) : mother (a) { cout << "son: int parameter\n\n"; }
derived classes
#include <iostream> using namespace std; class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} };
Although the constructors and destructors of the base class are not inherited themselves, its default constructorand its destructor are always called when a d or destroyed.
};
int main () {
CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; }
C++ Lecture
Inheritance between classes
A key feature of C++ classes is inheritance. Inheritance allows to create classes which are derived from other classes, so that they automatically include some of its "parent's" members, plus its own.
相关文档
最新文档