Как добиться многоуровневого наследования с классами - PullRequest
0 голосов
/ 18 октября 2018

Я пытаюсь сделать многоуровневое наследование от класса Shape к классам Rectangle, Circle и Triangle.От Rectangle мне нужно унаследовать класс Square и распечатать область, информацию и т. Д., А также эллипс из круга и равнобедренный из треугольника.До сих пор мои первые унаследованные классы работали нормально, но всякий раз, когда я пытаюсь заставить класс «внуков» работать, я не могу заставить его работать.Я понятия не имею, что я могу делать неправильно.Вот код:

 #include <iostream>
 using namespace std;

 class Shape{
 protected:
 string name;
 float area;

 public:
 Shape(string nm):name(nm){}

 //Getters
 string     getName(){    return name;    }
 float    getArea(){}

 //Setters
 virtual void    setArea(){}

 //Print
 virtual void printInfo()
 {
    cout << "Name: " << name << " Color: " << endl;
}

};

class Rectangle :  public Shape{
private:
float length, width;

public:
Rectangle(string nm, float l, float w):Shape::Shape(nm), length(l), width(w){}
Shape::getName();

//Setters
void setArea(){ area = length*width; }

void printInfo(){
    //Shape::printInfo();
    cout << "Name: " << name << " L: " << length << " W: " << width << " A: " << area << endl;
}
};

class Square : public Rectangle{

private:
float length;

public:
Square(string nm, float l):length(l),Rectangle::Rectangle(nm){}
float     getLength(){return length;}

//Setters
void setArea(){ area = length *length; }

};

class Circle : public Shape{
private:
float radius;
const float pi = 3.0;

public:
Circle(string nm, float r):Shape::Shape(nm), radius(r){}

//Setters
void setArea(){ area = pi*radius*radius; }

void printInfo(){
    //Shape::printInfo();
    cout << "Name: " << name << " R: " << radius << " A: " << area <<      endl;
}
};

 //class Ellipse : public Circle{
 //
 //private:
 //    float length, width, radius1, radius2;
   //
//public:
//    Ellipse(string nm, int clr, float l, float w);
//
//    //Setters
//void setArea(){ area = radius1 * radius2; }
//
//};

class Triangle : public Shape{
private:
float a, base, c, height;

public:
Triangle(string nm, float a, float b, float c, float h):Shape::Shape(nm), a(a), base(b), c(c), height(h){}

//Setters
void setArea(){ area = (base*height)/2; }

void printInfo(){
    //Shape::printInfo();
    cout << "Name: " << name << " Color: " << " A: " << a << " Base: " << base <<  " C: " << c  << " H: " << height << " P: " << " A: " << area << endl;
}
};

//class Isosceles : public Triangle{
//
//private:
//    float base, height;
//
//public:
//    Isosceles(string nm, int clr, float l, float w);
//
//    //Setters
//    void setArea(){ area = (base*height)/2; }
//
//}; 

int main() {

Rectangle r("Rectangle", 10, 20);
Circle c("Circle", 1);
Triangle tt("Triangle", 2, 2, 3, 3);
Square ss("Square", 10);

Shape* s;
Shape* t;
Shape* u;
Shape* v;
s = &r;
t = &c;
u = &tt;
v = &ss;

//Set and print area of Rectangle
s->setArea();
s->printInfo();

//Set and print area of Circle
t->setArea();
t->printInfo();

//Set and print area of Triangle
u->setArea();
u->printInfo();

//Set and print area of Rectangle
v->setArea();
v->printInfo();


return 0;
}

Я получаю сообщение об ошибке при настройке класса Square здесь:

class Square : public Rectangle{

private:
float length;

public:
Square(string nm, float l):length(l),Rectangle::Rectangle(nm){}

Я закомментировал классы Ellipse и Isosceles просто так, чтобы я мог настроитьПравильно возведи в квадрат и работай без них позже.Я впервые что-то спрашиваю, поэтому, если что-то не так, пожалуйста, дайте мне знать.Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 18 октября 2018

В вашем классе Square я считаю, что нашел одну ошибку ...

Попробуйте сделать следующее с вашим квадратным конструктором:

Square(string nm, float l):length(l),Rectangle::Rectangle(nm, l, l){} 

В отличие от того, что у вас было ... чтоисправит ошибки, которые вы получаете с классом Square.

Причина различия заключается в том, что когда вы передавали аргументы конструктору Rectangle из конструктора Square, вы оставляли некоторые аргументы не инициализированными (в конструкторе Rectangle).

...