2016-12-10 6 views
0

このコードを実行するように求められています。配列などを使用して別のクラスを出力する必要があります。私が知っている唯一の方法は、個々のクラスを個別に行うことです。以下は私が現時点で使用している方法です。C++配列とforループを使用して複数のクラスから出力する

Ground_Transport Gobj; 
Air_Transport Aobj; 
Sea_Transport Sobj; 
Car Cobj; 
Train Tobj; 
Bus Bobj; 


Gobj.estimate_time(); 
Gobj.estimate_cost(); 
cout << Gobj.getName() << endl; 

Bobj.estimate_time(); 
Bobj.estimate_cost(); 
cout << Bobj.getName() << endl; 

Sobj.estimate_time(); 
Sobj.estimate_cost(); 
cout<<Sobj.getName()<<endl; 

Aobj.estimate_time(); 
Aobj.estimate_cost(); 
cout << Aobj.getName() << endl; 

Cobj.estimate_time(); 
Cobj.estimate_cost(); 
cout << Cobj.getName() << endl; 

Tobj.estimate_time(); 
Tobj.estimate_cost(); 
cout << Tobj.getName() << endl; 

Transport_KL_Penang Kobj; 
cout << Kobj.getName() << endl; 

これを使用すると、特定のオブジェクト名を必要としない場合、あなたは倍数のジェネリックオブジェクトを作成し、以下のコードのように何かを書くことができますTransport_KL_Penang

#include <iostream> 
#include <string> 
using namespace std; 

class Transport_KL_Penang 
{ 
public: 
Transport_KL_Penang() {} 
virtual string getName() { 
    return Name;  
} 

int Time_in_hours1 ; 
int Time_in_hours2 ; 
int Cost_in_RM1 ; 
int Cost_in_RM2 ; 
void estimate_time() ; 
void estimate_cost() ; 

private: 
static string Name; 
}; 

void Transport_KL_Penang::estimate_time() 
{ 
cout << "It takes " << Time_in_hours1 << "-" << Time_in_hours2 << 
    " hours if you use " << Name << endl; 
} 

void Transport_KL_Penang::estimate_cost() 
{ 
cout << "It will cost around " << Cost_in_RM1 << "-" << Cost_in_RM2 << 
    "RM if you use " << Name << endl; 
} 
+0

コメントは議論の延長ではありません。この会話は[チャットに移動]されています(http://chat.stackoverflow.com/rooms/130276/discussion-on-question-by-hammad-saeed-cusing-array-and-for-loop-to-出力-fr)。 –

答えて

0

ヘッダファイルです:

#include <iostream> 
#include <cstdlib> 
#include <time.h> 

class Myclass { 
private: 
    int randTime; 
    float cost; 
public: 
    void estimate_time(){ 
     randTime = rand()%100; 
    } 
    void estimate_cost(){ 
     cost = randTime * 0.2; 
    } 
    float getEstimateCost(){ 
     return cost; 
    } 
}; 

int main(){ 
    srand(time(NULL)); 
    int numberOfObjects = 7; 
    Myclass obj[numberOfObjects]; 

    //input 
    for(int i = 0; i < numberOfObjects; i++){ 
      obj[i].estimate_time(); 
      obj[i].estimate_cost(); 
    } 
    // printing 
    for(int i = 0; i < numberOfObjects; i++){ 
      std::cout << obj[i].getEstimateCost() << std::endl; 
    } 
    return 0; 
} 
関連する問題