Witam, dopiero co zaczynam przygodę z podejściem obiektowym w c++ i napotkałem problem:
#include <string>
#include <iostream>
class Shape
{
protected:
std::string name;
public:
Shape(std::string name);
Shape();
~Shape();
void const setName(std::string name);
std::string getName();
virtual const double area() = 0 ;
private:
};
Shape::Shape() {
std::clog<< "konstruktor Shape jest wywoływany\n";
};
Shape::Shape(std::string name)
{
std::clog << "konstruktor Shape jest wywoływany\n";
this->name = name;
}
Shape::~Shape()
{
std::clog << "Destruktor Shape jest wywoływany\n";
}
void const Shape::setName(std::string name)
{
this->name = name;
}
std::string Shape::getName()
{
return name;
}
class Rectangle:public Shape
{
protected:
double width;
double height;
public:
Rectangle(std::string name, double width, double height);
~Rectangle();
Rectangle();
double const area();
private:
};
Rectangle::Rectangle() {
std::clog << "Wywoalano konstruktor Rectangle\n";
}
double const Rectangle::area()
{
return width*height;
}
;
Rectangle::Rectangle(std::string name, double width, double height)
{
//Shape(name);
std::clog << "Wywoalano konstruktor Rectangle\n";
this->name = name;
this->width = width;
this->height = height;
}
Rectangle::~Rectangle()
{
std::clog << "Wywoalano destruktor Rectangle\n";
}
class Square:public Rectangle
{
public:
Square();
Square(std::string name, double width);
double const area();
~Square();
private:
};
Square::Square()
{
std::clog << "Wywoalano konstruktor Rectangle\n";
}
Square::Square(std::string name, double width)
{
//Rectangle(name, width, width);
//Jeżeli użyję konstuktora Rectangle to Square przyjmuje "losowe" wartości
this->height = width;
this->width = width;
this->name = name;
}
double const Square::area()
{
return this->width*this->height;
}
Square::~Square()
{
}
int main()
{
//A
Rectangle a("Protokat", 2, 5);
std::clog << "Pole prostokata: " << a.area() << "\n";
Square b("Kwadrat",3);
std::clog << "Pole kwadratu: " << b.area() << "\n";
std::clog << "\n\n";
//B
Rectangle* aa{ new Rectangle("ProtokatB", 2, 5) };
Square *bb{ new Square("KwadratB", 3) };
std::clog << "Przed rzutowaniem: \n";
std::clog << "Pole prostokata: " << aa->area() << "\n";
std::clog << "Pole kwadratu: " << bb->area() << "\n";
std::clog << "\n\n";
a = b;
std::clog << "Po rzutowaniu(w gore): \n";
std::clog << "Pole prostokata: " << aa->area() << "\n";
std::clog << "Pole kwadratu: " << bb->area() << "\n";
std::clog << "\n\n";
bb = dynamic_cast<Square*>(aa);
std::clog << "Po rzutowaniu(w dol): \n";
std::clog << "Pole prostokata: " << a.area() << "\n";
std::clog << "Pole kwadratu: " << b.area() << "\n";
//pole prostokąta zostło zmienione na pole kwadratu
return 0;
}
Chodzi o to że wywołując konstruktor Square chcę w nim wywołać konstruktor Rectangle lecz wtedy Square zostaje zaincjalizowane losowymi wartościami, nie widzę błędu, a moje pomysły na poradzenie się wyczerpały już.