A może o taką strukturę Ci chodziło:
#include<iostream>
#include<string>
using namespace std;
class color{
protected:
string rgb;
public:
color(const string& rgb) : rgb(rgb) {}
virtual ~color() {}
string getColor() { return this->rgb; }
};
class shape : public color{
protected:
string name;
double height;
double base;
public:
shape(const string& name, double height, double base, const string& rgb)
: color(rgb), name(name), height(height), base(base) {}
virtual ~shape() {}
virtual double calculateField() = 0;
string getName(){ return this->name; }
};
class rectangle : public shape{
public:
rectangle(double height, double base, const string& rgb) :
shape("Rectangle", height, base, rgb) {}
double calculateField(){
return this->base * this->height;
}
};
int main() {
rectangle rec(12.4, 2 ,"#ff32cc");
shape *sh = &rec;
cout << "Name: " << sh->getName() << "\nField: " << sh->calculateField() << "\nColor: " << sh->getColor() << endl;
return 0;
}
Twój kod nie działa, bo niepotrzebnie psujesz sobie strukturę wielodziedziczeniem. Spokojnie kształt może dziedziczyć własności od koloru, a tak naprawdę nie tyle dziedziczyć co posiadać kolor więc dziedziczenie po klasie color
można spokojnie zastąpić obiektem wewnątrz klasy shape
. No ale zrobiłem tak jak Ty chciałeś żeby było.
Generalnie tak niżej jest bardziej prawidłowo, gdyż kształt posiada kolor, a nie jest kolorem sam w sobie:
#include<iostream>
#include<string>
using namespace std;
struct color{
string rgb;
color(const string& rgb) : rgb(rgb) {}
};
class shape{
protected:
string name;
double height;
double base;
color clr;
public:
shape(const string& name, double height, double base, const string& rgb)
: name(name), height(height), base(base), clr(color(rgb)) {}
virtual ~shape() {}
virtual double calculateField() = 0;
string getName(){ return this->name; }
string getColor(){ return this->clr.rgb; }
};
class rectangle : public shape{
public:
rectangle(double height, double base, const string& rgb) :
shape("Rectangle", height, base, rgb) {}
double calculateField(){
return this->base * this->height;
}
};
int main() {
rectangle rec(12.4, 2 ,"#ff32cc");
shape *sh = &rec;
cout << "Name: " << sh->getName() << "\nField: " << sh->calculateField() << "\nColor: " << sh->getColor() << endl;
return 0;
}