On-line: гостей 0. Всего: 0 [подробнее..]
Программисты всех стран, объединяйтесь!

АвторСообщение



ссылка на сообщение  Отправлено: 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 ?

Спасибо: 0 
ПрофильЦитата Ответить
Ответов - 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();



Спасибо: 0 
ПрофильЦитата Ответить
Ответ:
1 2 3 4 5 6 7 8 9
большой шрифт малый шрифт надстрочный подстрочный заголовок большой заголовок видео с youtube.com картинка из интернета картинка с компьютера ссылка файл с компьютера русская клавиатура транслитератор  цитата  кавычки моноширинный шрифт моноширинный шрифт горизонтальная линия отступ точка LI бегущая строка оффтопик свернутый текст

показывать это сообщение только модераторам
не делать ссылки активными
Имя, пароль:      зарегистрироваться    
Тему читают:
- участник сейчас на форуме
- участник вне форума
Все даты в формате GMT  3 час. Хитов сегодня: 25
Права: смайлы да, картинки да, шрифты да, голосования нет
аватары да, автозамена ссылок вкл, премодерация откл, правка нет