### a question about operator *= function

It's a program about operator function(*=).
Question:
Declare a class for Rectangle and Declare a class for Triangle.So compute area of this two and Declare a operator *= function that it multiplies area of triangle and rectangle and place value in triangle object.
I wrote this incomplete.Why should we write operator *= function in triangle class? In triangle class ,we don't access to rectangle area.plz help me.
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748`` ``````#include #include using namespace std; class triangle; class rect { int x,y,s1; public: void input(); int calc(); }; void rect::input() { cout<<"Enter Area:"; cin>>x>>y; } int rect::calc() { return s1=x*y; } class rect; class triangle { int a,h,s2; public: void input(); int calc(); }; void triangle::input() { cout<<"Enter Base and height"; cin>>a>>h; } int triangle::calc() { return s2=(a*h)/2; } triangle triangle::operator *=(rect o2) int main() { triangle o1; rect o2; o1.input(); o1.calc(); o2.input(); o2.calc(); o1*=o2; }``````
Last edited on
Why can't triangle access the area of the rect? Just implement a "getter"

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364`` ``````#include class poly { private: virtual void calc_area() = 0; protected: double m_base; double m_height; double m_area; public: double get_area() { return m_area; } poly( double base, double height ) : m_base(base), m_height(height) {} }; class rect : public poly { private: virtual void calc_area() { m_area = m_base * m_height; } public: rect ( double base, double height) : poly(base,height) { calc_area(); } }; class triangle : public poly { private: virtual void calc_area() { m_area = 0.5 * m_base * m_height; } public: triangle (double base, double height) : poly(base,height) { calc_area(); } double operator*= (rect& r) { m_area *= r.get_area(); m_base = 2 * m_area / m_height; return m_area; } }; int main() { rect r(1,2); triangle t(3,4); std::cout << r.get_area() << std::endl; std::cout << t.get_area() << std::endl; std::cout << (t *= r) << std::endl; }`````` ```2 6 12 Press any key to continue . . .```
Last edited on
Topic archived. No new replies allowed.