a question about operator *= function
Dec 2, 2012 at 3:27pm UTC
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <iostream>
#include <string>
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 Dec 2, 2012 at 4:19pm UTC
Dec 2, 2012 at 4:23pm UTC
Why can't triangle access the area of the rect? Just implement a "getter"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#include <iostream>
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 Dec 2, 2012 at 4:26pm UTC
Topic archived. No new replies allowed.