C++ polygon rectangle and triangle inheritance -
i trying create polygon class , rectangle , triangle inherit first. polygon class has height , width variables want them be given values within constructor. then, rectangle , triangle have area calculation methods. then, utilize main() give examples. use:
#include <iostream> using namespace std; class polygon { public: polygon(int, int); protected: int height; int width; }; class rectangle: public polygon { public: void calc_area(); }; class triangle: public polygon { public: void calc_area(); }; polygon::polygon(int a, int b) { height = a; width = b; } void rectangle::calc_area() { cout << "rectangle area: " << (height*width) << endl; } void triangle::calc_area() { cout << "triangle area: " << (height*width/2) << endl; } int main() { rectangle s1(5, 2); triangle s2(5, 2); s1.calc_area(); s2.calc_area(); }
but while looks ok newbie eyes, series of errors:
12 base of operations polygon' non-default constructor in class without constructor `
36 no matching function phone call `rectangle::rectangle(int, int)
37 no matching function phone call `triangle::triangle(int, int)'
can give me tips? seen, new c++...
you shouldn't phone call constructor utilize .
, such as:
rectangle s1; triangle s2; s1.polygon(5, 2); s2.polygon(5, 2);
try way:
rectangle s1(5, 2); triangle s2(5, 2);
and should add together constructor rectangle
, triangle
respectively:
class rectangle: public polygon { public: rectangle(int height, int width):polygon(height, width){} void calc_area(); }; class triangle: public polygon { public: triangle(int height, int width):polygon(height, width){} void calc_area(); };
c++ inheritance
No comments:
Post a Comment