1.Make a class whose objects each represent a battery. The only attribute an object will have is the battery type (one letter). Also, the class has to include the following services for its objects: determine if two batteries are equal change battery type get battery type display battery information 2.Make a class whose objects each represent a box of batteries (use dynamic memory and draw the class diagram). Also, the class has to include the following services for its objects: -show what's in the box -get how many kinds of batteries are in the box -determine if two boxes are equal C++.
Code :
#include <iostream>
using namespace std;
const int MAX_SIZE = 10;
class Battery
{
private:
char m_cBattryType;
public:
char getBattryType()
{
return m_cBattryType;
}
void setBatteryType(char cBatteryType)
{
m_cBattryType = cBatteryType;
}
void DisplayInfo()
{
cout << m_cBattryType << endl;
}
bool operator ==(Battery battery)
{
return m_cBattryType == battery.getBattryType();
}
Battery(char cBatteryType)
{
m_cBattryType = cBatteryType;
}
};
class BatteryBox
{
private:
Battery* m_batteryArr[MAX_SIZE];
int m_iCount;
public:
char getCount()
{
return m_iCount;
}
BatteryBox()
{
m_iCount = 0;
for (int i = 0; i < MAX_SIZE; i++)
m_batteryArr[i] = NULL;
}
void DisplayInfo()
{
for (int i = 0; i < m_iCount; i++)
{
m_batteryArr[i]->DisplayInfo();
cout << i << endl;
}
}
void AddBattery(Battery *b)
{
m_batteryArr[m_iCount++] = b;
}
bool operator ==(BatteryBox batteryBox)
{
if (this->m_iCount != batteryBox.getCount())
return false;
bool bResult = false;
for (int i = 0; i < m_iCount; i++)
{
bResult = (*this->m_batteryArr[i] == *batteryBox.m_batteryArr[i]);
if (bResult == false)
break;
}
return bResult;
}
~BatteryBox()
{
for (int i = 0; i < m_iCount; i++)
{
Battery *ptr = m_batteryArr[i];
if (ptr)
{
delete ptr;
ptr = NULL;
}
}
}
};
using namespace std;
int main()
{
Battery* b1 = new Battery('a');
Battery* b2 = new Battery('b');
Battery* b3 = new Battery('a');
Battery* b4 = new Battery('b');
cout << "Show battery b1 information ";
b1->DisplayInfo();
cout << endl;
cout << "Show battery b3 information ";
b3->DisplayInfo();
cout << endl;
if (*b1 == *b3)
{
cout << "batteries are same" << endl;;
}
else
{
cout << "batteries are different" << endl;
}
BatteryBox bx1;
BatteryBox bx2;
bx1.AddBattery(b1);
bx1.AddBattery(b2);
bx2.AddBattery(b1);
bx2.AddBattery(b2);
cout << "Show battery box bx1 information ";
bx1.DisplayInfo();
cout << endl;
cout << "Show battery box bx2 information ";
bx2.DisplayInfo();
cout << endl;
if (bx1 == bx2)
{
cout << "battery boxes are same" << endl;;
}
else
{
cout << "different" << endl;
}
}
Get Answers For Free
Most questions answered within 1 hours.