Я пытаюсь заставить один класс работать с другим классом. Предполагается уменьшить член другого класса.
мой первый класс
class Bike
{
private:
int miles;
Speedometer speedom;
static int fuelCount;
public:
Bike();
Bike(int, Speedometer*); //Problem occurs here
~Bike();
int getMiles();
int getFuelCount();
void incrementMiles();
};
int Bike::fuelCount = 0;
Bike::Bike()
{
miles = 0;
fuelCount++;
}
Bike::Bike(int m, Speedometer * spm) //This is where I am having problems
{
miles = m;
speedom = &spm;
}Bike::~Bike()
{
cout << "The Bike's destructor is running." << endl;
fuelCount--;
}
int Bike::getMiles()
{
return miles;
}
int Bike::getFuelCount()
{
return fuelCount;
}
void Bike::incrementMiles()
{
miles++;
if (miles == 999999)
miles = 0;
}
Другой класс, который должен быть включен в первый:
Class Speedometer
{
private:
int fuel;public:
Speedometer();
Speedometer(int);
~Speedometer();
int getFuel();
void incrementFuel();
void decrementFuel();
};Speedometer::Speedometer()
{
fuel = 0;
}
Speedometer::Speedometer(int f)
{
fuel = f;
}int Speedometer::getFuel()
{
return fuel;
}void Speedometer::incrementFuel()
{
if (fuel <= 15)
fuel++;
}
void Speedometer::decrementFuel()
{
if (fuel > 0)
fuel--;
}
Они должны работать вместе. Велосипед должен уметь работать со спидометром. Это должно уменьшить количество топлива на спидометрах на один галлон на каждые 24 мили пробега.
Предполагается, что это совокупные отношения, а не композиция.
Пожалуйста, помогите мне просто понять, как сделать эти отношения и как их следует называть.
Заранее спасибо.
вот моя основная функция
кстати — у меня есть все права #include, я просто не перечислил их здесь
int main(int argc, char *argv[])
{
Speedometer a(999970, spd);
for(int count = 0; count <=24; count++)
a.decrementMiles();
while (a.getFuel() > 0)
{
a.incrementMiles();
cout<< "Miles:" << a.getMiles() << endl;
cout<< "Fuel:" << a.getFuel() << endl;
}
return 0;
}
У вас есть большое количество вопросов здесь.
Прежде всего, в вашем main()
конструируешь Speedometer
объект с конструктором вы не реализовали. Определенные вами конструкторы — это конструктор по умолчанию и Speedometer(int)
, Вы тогда звоните Speedometer(int, ???)
, ???
являющийся spd
потому что вы не заявляете spd
в любом месте кода, который вы предоставили, поэтому мы понятия не имеем, что это такое.
Действительно невозможно сказать, что не так с вашим кодом в его текущем состоянии.
Как написано, вы сделали композицию; Speedometer
является часть Bike
так как это поле. Чтобы сделать это агрегацией, сделайте Bike
держать указатель в Speedometer
, Обратите внимание, что, как следствие, вам, вероятно, понадобится Bike
создать или получить начальный Speedometer
(может быть NULL
или передать его в конструктор), и вы можете добавить методы доступа к Bike
для того, чтобы добавить / удалить / изменить Speedometer
,
Bike
возможно, также необходимо знать, как избавиться от Speedometer
правильно, чтобы избежать утечки.
[edit 2] Также, как указал @ cjm571, ваш main
Функция создает и работает непосредственно на «бестелесном» Speedometer
, Разве это не должно быть на Bike
? 🙂
#include <iostream>
using namespace std;class Bike
{
private:
int miles;
static int fuelCount;
// Speedometer speedom;
public:Bike();
Bike(int); // Speedometer *); check comment on line 82
~Bike();int getMiles();
int getFuelCount();
void incrementMiles();
};
int Bike::fuelCount = 0;
Bike::Bike()
{
miles = 0;
fuelCount++;
}
Bike::Bike(int m)//Speedometer (*spm) I don't see the purpose of this in the current state of the program, I may not be seing the whole picture
{
miles = m;
/* speedom = spm; remember, there must be a parent and a child class, at the current state you'r trying
to call a child from parent, the child class has not been defined, so i switched them and now Bike is a chiled. */
}Bike::~Bike()
{
cout << "The Bike's destructor is running." << endl;
fuelCount--;
}
int Bike::getMiles()
{
return miles;
}
int Bike::getFuelCount()
{
return fuelCount;
}
void Bike::incrementMiles()
{
miles++;
if (miles == 999)
miles = 0;
}class Speedometer
{
private:
int fuel;public:
Speedometer();
Speedometer(int f);
int getFuel();
Bike theBike; // This is what you needed in order to make incrementMiles to work.
void incrementFuel();
void decrementFuel();
};Speedometer::Speedometer()
{
fuel = 0;
}
Speedometer::Speedometer(int f)
{
fuel = f;
}int Speedometer::getFuel()
{
return fuel;
}void Speedometer::incrementFuel()
{
if (fuel <= 15)
fuel++;
}
void Speedometer::decrementFuel()
{
if (fuel > 0)
fuel--;
}int main(int argc, char *argv[])
{
Speedometer a(999); //You never declared this, did you mean spm???
for(int count = 0; count <=24; count++)
a.theBike.incrementMiles();
while (a.getFuel() > 0)
{
a.theBike.incrementMiles();
cout<< "Miles:" << a.theBike.getMiles() << endl;
cout<< "Fuel:" << a.getFuel() << endl;
}
cin.get();
return 0;
} //There is no break declared (that i can see at least) so the program runs an infinite loop
// Don't want to add too many things to it, I don't know what your plan is.
// Hoping to have made it clearer.