2017-10-15 14 views
0

英語は私の母国語ではありません。私は多くの間違いをしないことを願っています。私は可能な限り明確になるように最善を尽くします!多態性を使用して派生クラスの値を基本クラスにコピー

私は、基本クラスの私のmain.cppに

int main() 
{ 
     diesel diesel_engine; 
     const engine &e = diesel_engine; 
     std::cout<<e.getWeight()<<e.getName()<<std::endl; 
     return 0; 
} 

1-

class engine 
{ 
private : 
    std::string name; 
    double weight; 

public: 
    engine(); 
    ~engine(); 
    std::string getName() const; 
    int getWeight() const 
}; 

std::string engine::getName() const{ 
return this->name; 
} 

int engine::getWeight() const{ 
return this->weight; 
} 

と派生クラス

class diesel : public engine 
{ 
private: 
    std::string name; 
    double weight; 

public: 
    diesel(); 
    ~diesel(); 
}; 

diesel::diesel(){ 
this->name = Diesel; 
this->weight = 500.00; 
} 

を持っている私はdiesel_engineという名前のディーゼルクラスを作成する必要があります。

ディーゼルエンジンの2つの値を基準とした新しいエンジンへの値??

const engine &e = diesel_engine;と呼ぶと、diesel_engineの値(名前と重量)を新しいエンジンにコピーする必要があります。

「e」の重みは500.00で、名前は「ディーゼル」である必要があります。

これを行うには多形性をどのように使用できますか?

この質問をお読みいただきありがとうございます。

+0

正しいエンジンの名前を出力します。 –

+0

大丈夫です!私が本当に理解しているかどうかは確かではありません –

+0

ありがとうございます。メンバ変数 'name'や' weight'のように 'protected'修飾子を持たなければなりません。派生クラスでは再宣言されません。何が起こるのですか?コンパイル時エラー、実行時エラー、 'main'の最後に' engine'の値をチェックする方法はありますか? – dlatikay

答えて

1

は、クラス宣言

class Engine 
{ 
private: 
    float weight_; 
    std::string name_; 
public: 
    Engine(float weight, std::string name) : weight_(weight), name_(name){}; 
    std::string GetName() const { return name_;} 
}; 

class Diesel : public Engine 
{ 
public: 
    Diesel(float weight, std::string name) : Engine(weight, name){} 
}; 

で始めることができますので、私たちがここに持っているものたちのbase classされ、その後、我々はEngineから私たちのDiesel classDiesel継承を定義し、その基底クラスに引数を渡すEngineクラスです。これを使用するには今すぐ

eng.GetName()

Diesel disel_engine(0.0, "diesel engine"); 
const Engine& eng = disel_engine; 
cout << eng.GetName(); 

コールは、クラスの宣言を追加します素晴らしいことだ

Demo Here

+0

私の質問に答えてくれてありがとう!今私はそれを使用する方法を理解する!もう一度! –

+1

私は良いC + +の本を取得することをお勧めし、なぜこれが動作するかを完全に理解する。 –

関連する問題