標籤:c++ 派生 類 繼承
多繼承格式:
class 類名:繼承方式1 基類1,繼承方式2 基類2,........
#include<iostream>using namespace std;class X{ int x;public: X(int a = 0) {x = a;cout<<"constructing X "<<x<<endl;} void set_x(int a) {x = a;} void show_x() {cout<<"x = "<<x<<endl;} ~X() {cout<<"destructing X "<<x<<endl;}};class Y{ int y;public: Y(int a = 0) {y = a;cout<<"constructing Y "<<y<<endl;} void set_y(int b) {y = b;} void show_y() {cout<<"y = "<<y<<endl;;} ~Y() {cout<<"destructing Y "<<y<<endl;}};class Z:public X,public Y//多繼承{ int z;public: Z(int a = 0,int b = 0,int c = 0):X(a),Y(b) { z = c; cout<<"constructing Z "<<z<<endl; } void set_xyz(int a,int b,int c) { set_x(a); set_y(b); z = c; } void show_z() { cout<<"z = "<<z<<endl; } void show() { show_x(); show_y(); cout<<"z = "<<z<<endl;//類內可直接用 } ~Z() {cout<<"destructing Z "<<z<<endl;}};int main(){ Z obj1(3,4,5); Z obj2; obj2.set_xyz(10,20,30); obj1.show_x(); obj1.show_y(); obj1.show_z(); obj2.show(); return 0;}
[c++]多繼承