Ich habe die meisten der Code/Zuordnung herausgefunden, hier ist ein Teil der „To-Do“ Ich kann nicht herausfinden:Wie legen Sie ein Zeichenfolgendatenelement aus einer Basisklasse mit einer abgeleiteten Klasse fest?
- Die abgeleiteten Klassen stellen Sie den m_type, aber beachten Sie, gibt es keine setType Funktion zu tun so (und Sie können nicht hinzufügen).
Hier ist mein Code (nichts in Haupt geändert werden kann):
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <string>
const double PI = 3.14159265359;
class Geometry
{
public:
Geometry(std::string name)
:m_name(name)
{
}
virtual double computeVolume() = 0;
virtual double computeSurfaceArea() = 0;
std::string getName() { return m_name; }
std::string getType() { return m_type; }
protected:
std::string m_name;
std::string m_type;
};
class Box : public Geometry
{
public:
Box(std::string name, double length, double width, double height)
: Geometry(name), m_length(length), m_width(width), m_height(height)
{
}
virtual double computeSurfaceArea()
{
return (2 * (m_height * m_width)) + (2 * (m_height * m_length)) + (2
* (m_length * m_width));
}
virtual double computeVolume()
{
return m_length * m_width * m_height;
}
protected:
double m_length;
double m_width;
double m_height;
};
class Sphere : public Geometry
{
public:
Sphere(std::string name, double radius)
:Geometry(name), m_radius(radius)
{
}
virtual double computeVolume()
{
return (4.0/3.0) * PI * (m_radius * m_radius * m_radius);
}
virtual double computeSurfaceArea()
{
return 4 * PI * (m_radius * m_radius);
}
protected:
double m_radius;
};
void report(Geometry* obj)
{
std::cout << "----- Geometry Report -----" << std::endl << std::endl
<< "Type: " << obj->getType() << std::endl
<< "Name: " << obj->getName() << std::endl
<< "Volume " << obj->computeVolume() << std::endl
<< "Surface Area " << obj->computeSurfaceArea() << std::endl <<
std::endl;
}
int main()
{
std::vector<Geometry*> items;
items.push_back(new Box("Box 1", 1, 2, 3));
items.push_back(new Box("Box 2", 2, 3, 4));
items.push_back(new Sphere("Sphere 1", 5));
items.push_back(new Sphere("Sphere 2", 6));
for (int i = 0; i < items.size(); i++)
{
report(items[i]);
}
system("PAUSE");
return 0;
}
Dank
Ich hatte es wäre einfach ein Gefühl verwendet werden! Danke für die Hilfe! – Hanna369