Автор | Сообщение |
|
Отправлено: 27.09.12 17:31. Заголовок: virtual function()
[code] #include <iostream> #include <string> using namespace std; class A{ private: string AFood; public: A( string theAFood){ AFood = theAFood; } virtual void displayFoodType() const{ } virtual string getAFood() const { return AFood; } }; class B : public A{ private: string BFood; public: B( string theBFood , string theAFood ) : A( theAFood ){ BFood = theBFood; } virtual string getBFood() const{ return BFood; } virtual void displayFoodType() const{ cout << "---------------------\nA is for " << getAFood() << "\nB is for " << getBFood() << endl; } }; class C : public B{ private: string CFood; public: C( string theCFood , string theBFood , string theAFood ) : B( theBFood , theAFood ){ CFood = theCFood; } virtual string getCFood() const { return CFood; } virtual void displayFoodType() const{ cout << "---------------------\nA is for " << getAFood() << "\nB is for " << getBFood() << "\nC is for " << getCFood() << endl; } }; int main(){ B B1( "Burger" , "Avocado" ); B B2( "Bean " , "Acorn" ); C C1( "Cheese" , "Blueberry" , "Almond" ); C C2( "Cherry" , "Banana" , "Apple" ); cin.get(); return 0; }[/code] Output should be : [code]--------------------- A is for Acorn B is for Bean --------------------- A is for Almond B is for Blueberry C is for Cheese [/code] How should i implement it to using the virtual function? tried it but keep fail , because yesterday only learn , hard to get it , pass by constructor i think mine is correct already so whats my error ?
|
|
|
Ответов - 1
[только новые]
|
|
|
Отправлено: 27.09.12 18:30. Заголовок: You defined four obj..
You defined four objects but as I see the output is shown only for two objects. So it is not clear what shall do your code. It is better to write the code correctly from the very begining. For example the constructor for class A should look the following way A( const string &theAFood) : AFood( theAFood ) { /* empty body */ } Also the destructor shall be virtual. Further there is no any sense to declare member functions getAFood, getBFood, and getCFood as virtual because you did not redefine them in derived classes. When you use public inheritance the base class should define the common interface for its derived classes. And why do you can not to get the output you showed by simply calling method displayFoodType? For example B2.displayFoodType(); C1.displayFoodType();
|
|
|