2016-11-17 6 views
0

私はインベントリシステムを作成しており、派生物を使用してさまざまなアイテムを作成しようとしているため、子要素に親要素と特殊要素を持つことができます。 私は下に書いたように、現時点では「私は親です」が印刷されていますが、「私は子供です」と印刷するようにしています。また、stuffToSayの子の定義がないため、私は親です "ありがとう!このようなC++の継承と変数の変更

using namespace std; 


class myParent { 
public: 
    virtual void saySomething() { 
     cout << stuffToSay; 
    } 
    string stuffToSay = "I'm a parent"; 

private: 
}; 

class myDerivitive : public myParent{ 

public: 
    myDerivitive() {}; 
    string stuffToSay = "I'm a kid"; 
private: 

}; 


int main() { 
    myParent* people[] = { 
     new myDerivitive() 
    }; 

    cout << people[0]->stuffToSay; 


    system("pause"); 
} 

答えて

0

何かが正常にあなたのクラスのコンストラクタを使用して行われ、子クラスは、それはこのように行うことができるため、あなたが探しているものを行うには、その親クラスのすべての変数があります。

using namespace std; 


class myParent { 
public: 
    myParent() { 
     stuffToSay = "I'm a parent" 
    } 
    virtual void saySomething() { 
     cout << stuffToSay; 
    } 
    string stuffToSay; 

private: 
}; 

class myDerivitive : public myParent{ 

public: 
    myDerivitive() { 
     stuffToSay = "I'm a kid"; 
    }; 
private: 

}; 


int main() { 
    myParent* people = new myDerivitive(); 

    cout << people->stuffToSay(); 

    delete people; // Simplified to a single pointer and remember to delete it 
    people = NULL; 

    system("pause"); 
} 

クラスの詳細については、このリンクをご覧ください:あなたの派生クラスがそのPA以来、「stuffToSay」変数を持っているであろうから http://www.cplusplus.com/doc/tutorial/classes/

このリンクは、相続の理解に役立ちます家賃はそれを持っていた:

http://www.cplusplus.com/doc/tutorial/inheritance/

2

それがどのように動作するかではない厥。親のsaySomethingは、派生クラスの文字列について何も知らず、メンバ変数は仮想ではありません。

あなたはそれを行うことができます。この

#include <iostream> 
#include <string> 

struct myParent { 
    void saySomething() { 
     cout << getSomething(); 
    } 
    virtual std::string getSomething(){ return "I'm a parent"; } 
    virtual ~myParent(){} // virtual destructor is needed 
}; 

struct myDerived : myParent { 
    virtual std::string getSomething(){ return "I'm the derived"; } 
}; 

int main() { 
    myParent* p = new myDerived(); 
    p->saySomething(); 
    delete p; // dont forget to delete !! 
} 
+0

あーだから、これを行うことができますコードが、[今すぐ修正する必要があります](http://ideone.com/nTEpqm);) – user463035818

0

のようにCでvirtualまたはオーバーライドされた変数++のようなものはありません。その種の多型はメソッドにのみ適用されます。

struct parent { 
    virtual void saySomething() { 
     cout << "I'm a parent!\n"; 
    } 
}; 

struct child: parent { 
    void saySomething() override { 
     cout << "I'm a child!\n"; 
    } 
}; 

それとも、間接のレイヤーを追加することによって、より多くのあなたの現在の構造のようなもので、それを解決することができます::私はすべてのエラーでより多くのdownvotesを期待していた

struct parent { 
    void saySomething() { 
     cout << thingToSay() << '\n'; 
    } 

private: 
    virtual string thingToSay() { return "I'm a parent!"; } 
}; 

class child: parent { 
    virtual string thingToSay() { return "I'm a child!"; } 
}; 
関連する問題