我试图在Passenger和Bus类之间进行聚合,[wheel,door,engine]和Bus class之间的组合,[car,bus]和Vehicle的简单关联。此外,Driver与Car相关联。但我不知道如何用C ++代码编写它。我的程序在语法上是正确的,但给出了运行时错误。请帮我。
#include<iostream>
#include<string>
using namespace std;
class Vehicle
{};
class Bus
{
Door door;
Wheel wheel;
Engine engine;
Passenger P;
string busNo;
int SeatingCapacity, SeatsReservedSofar;
public:
int GetSeatingCapacity();
void SetSeatingCapacity(int bCap);
string GetBusNo();
void SetBusNo(string bNo);
void ReserveSeat(Passenger P);
void DisplayInfo();
};
class Passenger
{
string Name;
char Gender;
public:
void SetPassengerName(string name);
string GetPassengerName();
void SetGender(char gender);
char GetGender();
};
class Car
{};
class Driver
{
};
class Wheel
{
};
class Door
{
};
class Engine
{
};
////////////////////////////////////
//Definition of Functions
////////////////////////////////////
Bus::Bus()
{
cout<<"Creating a new bus..."<<endl;
}
void Bus::SetSeatingCapacity(int bCap)
{
if(bCap>20 && bCap<50)
SeatingCapacity=bCap;
}
void Bus::SetBusNo(string bNo)
{
int len=bNo.length();
if(len>2 && len<5)
busNo=bNo;
}
void Passenger::SetPassengerName(string pname)
{
int len=pname.length;
if(len>0 && len<40)
Name=pname;
}
void Passenger::SetGender(char pgender)
{
if(pgender=='m' || pgender=='f')
Gender=pgender;
}
void Bus::ReserveSeat(Passenger P)
{
int capacity = GetSeatingCapacity(), rem;
if(capacity != SeatsReservedSofar)
{
SeatsReservedSofar++;
cout<<endl<<"Seat reserved for passenger";
rem=capacity-SeatsReservedSofar;
cout<<endl<<"Remaining Capacity : "<<rem;
}
else
{
cout<<endl<<"Seat reservation failed. No space left. ";
}
}
int main()
{
Bus abus;
cout<<"Enter max capacity of bus for passengers : ";
int capacity;
cin>>capacity;
abus.SetSeatingCapacity(capacity);
cout<<endl<<"Enter the bus registration no : ";
string regno;
std::getline(std::cin,regno);
cin.ignore();
abus.SetBusNo(regno);
cout<<endl<<".....Bus is created successfully. "<<endl<<endl;
string pname;
Passenger passenger;
char gender;
cout<<"Enter the passenger name: ";
std::getline(std::cin, pname);
cin.ignore();
passenger.SetPassengerName(pname);
cout<<"Enter the passenger gender <m for male and f for female>";
cin>>gender;
passenger.SetGender(gender);
abus.ReserveSeat(passenger);
char quest;
for(quest='y'; quest == 'y'; )
{
cout<<endl<<endl<<"Do you want to add more passengers? (y/Y for yes and another character for no)? ";
char quest;
cin>>quest;
}
system("pause");
}
答案 0 :(得分:2)
首先我认为你的程序无法编译,为什么?
如果有预订系统,您可以考虑使用某种类型的Seat类来保存有关预订的信息,例如Passanger指针或类似的东西。
要保留有关多个Passangers的信息,您可以使用类似std :: vector&lt;的std ::的weak_ptr&LT;通勤&GT; &GT;
拥有多个轮子 - 类似于std :: array&lt;轮&GT; - 座位相同,std :: array&lt;座椅&GT;