C++カリキュラムジョブ継承と派生(motorcycleクラス設計(ダミーベースクラス))
12469 ワード
まず、タイトル【問題の説明】は、プライベートメンバーmaxspeedとweight、パブリックメンバーrun()とstop()を持つベースクラスvehicleという名前です.、および構造と構造関数.vehicleからbicycleとmotorcarが派生し、bicycleにはプライベートメンバーheight、motorcarにはプライベートメンバーseatnum、およびそれぞれの構造関数と構造関数があります.bicycleとmotorcarからmotorcycleを派生させ,継承に及ぼす虚ベースクラスの影響を観察した.motorcycleのオブジェクトを定義し、run()とstop()をそれぞれ呼び出し、構造/構造関数の呼び出し状況を観察します.注意:コンストラクション関数とコンストラクション関数はcout文であり、どのコンストラクション/コンストラクション関数が呼び出されるかを示します.この問題の重点と難点は構造関数の設計にあり,ベースクラスと最も遠いベースクラスにパラメータをどのように伝達するかを考慮する必要がある.
そしてコード
まとめ:ダミーベースクラスvirtualの位置は、最後の派生クラスの定義ではありません(最初はこのように書かれているので、問題が発生します).各クラスの初期化には、前のクラスの初期化が含まれます.
そしてコード
#include
using namespace std;
class vehicle
{
int maxspeed, weight;
public:
void run() { cout << "vehicle run" << endl; }
void stop() { cout << "vehicle stop" << endl; }
vehicle(int speed = 0, int wei = 0) { maxspeed = speed; weight = wei; cout << "vehicle constructor called. maxspeed:" << maxspeed << "; weight" << weight << endl; }// ,
~vehicle(){ cout<<"vehicle destructor called. maxspeed:" << maxspeed << "; weight" << weight << endl; }
};
class bicycle :virtual public vehicle// , ,
{
int height;
public:
~bicycle() { cout << "bicycle destructor called. height:" << height << endl; }
bicycle(int speed, int wei, int hei) :vehicle(speed, wei), height(hei) { cout << "bicycle constructor called. height:" << height << endl; }// ( )
};
class motorcar :virtual public vehicle//
{
int seatnum;
public:
motorcar(int speed, int wei, int seat) :vehicle(speed, wei), seatnum(seat) { cout << "motorcar constructor called. seatnum:" << seatnum << endl; }
~motorcar() { cout << "motorcar destructor called. seatnum:" << seatnum << endl; }
};
class motorcycle : public bicycle, public motorcar// , , virtual
{,=
public:
motorcycle(int hei, int seat, int speed, int wei) :vehicle(speed, wei), bicycle(speed, wei, hei), motorcar(speed, wei, seat) { cout << "motorcycle constructor called" << endl; }// !!
~motorcycle() { cout << "motorcycle destructor called" << endl; }
};
int main(int argc, char* argv[])
{
motorcycle m(1, 2, 3, 4);//1 height,2 setnum,3 maxspeed,4 weight
m.run();
m.stop();
return 0;
}
まとめ:ダミーベースクラスvirtualの位置は、最後の派生クラスの定義ではありません(最初はこのように書かれているので、問題が発生します).各クラスの初期化には、前のクラスの初期化が含まれます.