【问题标题】:C++ Using array and for loop to output from multiple classesC ++使用数组和for循环从多个类输出
【发布时间】:2016-12-10 05:43:59
【问题描述】:

我被要求执行此代码,我需要使用数组或类似的东西来打印出不同的类。我知道的唯一方法是单独做每一堂课,有一种更快的方法可以做到这一点。以下是我目前使用的方式。

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;
 }

【问题讨论】:

标签: c++ arrays class for-loop


【解决方案1】:

如果您不需要特定的对象名称,您可以编写如下代码,创建多个泛型对象:

#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; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    相关资源
    最近更新 更多