Hej! Przerabiam sobie polimorfizm i używanie abstrakcyjnych funkcji wirtualnych. Zaczyna brakować mi pomysłów co zrobiłem nie tak, a pewnie to jakaś głupota. Pomyślałem, że zwrócę się do Was o pomoc. :)
Napisałem program, który ma docelowo przy pomocy użycia abstrakcyjnej klasy Figure wywoływać odpowiednie obliczenia/informacje dla kwadratu, prostopadłościanu i odcinka. Program się odpala, natomiast wywołuje wyłącznie napis "Calculate" z klasy abstrakcyjnej Figure.
Figure.h
#pragma once
class Figure
{
public:
Figure() {};
virtual void calculate()
{
std::cout << "Calculate: \n";
}
~Figure() {};
};
Segment.h
#pragma once
#include "Figure.h"
class Segment : public Figure
{
private:
double x;
public:
Segment(double newX = 0)
{
this->x = newX;
}
void calculate(double x)
{
std::cout << "Segment length: " << x << std::endl;
}
};
Square.h
#pragma once
#include "Figure.h"
class Square : public Figure
{
private:
double x;
public:
Square(double newX = 0)
{
this->x = newX;
}
void calculate(double x)
{
std::cout << "Perimeter of the square: " << 4 * x << std::endl;
std::cout << "Square Area: " << x * x << std::endl;
}
};
Cuboid.h
#pragma once
#include "Figure.h"
class Cuboid : public Figure
{
private:
double x;
double y;
double z;
public:
Cuboid(double newX = 0, double newY = 0, double newZ = 0)
{
this->x = newX;
this->y = newY;
this->z = newZ;
}
void calculate(double x, double y, double z)
{
std::cout << "Permiter of a cuboid: " << 4 * (x+y+z) << std::endl;
std::cout << "Cuboid area: " << 2*(x*y) + 2*(x*z) + 2*(y*z) << std::endl;
std::cout << "The cuboid volume: " << x * y * z << std::endl;
}
};
Main.cpp
#include <iostream>
#include "Figure.h"
#include "Segment.h"
#include "Square.h"
#include "Cuboid.h"
int main()
{
Figure** tab = new Figure * [6];
tab[0] = new Segment();
tab[1] = new Segment(5);
tab[2] = new Square();
tab[3] = new Square(10);
tab[4] = new Cuboid();
tab[5] = new Cuboid(5,10,15);
for (int i = 0; i < 6; i++) {
tab[i]->calculate();
delete tab[i];
}
delete[] tab;
getchar();
return 0;
}