Re: Type conversion function for user type again.
On 18 Maj, 03:03, zaemi...@gmail.com wrote:
I got a good answer here I have still confusing part.
I have two very simple classes
class DRect
{
private :
double x0, y0, x1, y1;
public :
DRect(double a, double b, double c, double d) : x0(a), y0(b),
x1(c), y1(d) {}
void Union(const DRect* p)
{
x0 = MIN(x0, p->x0);
y0 = MIN(y0, p->y0);
x1 = MAX(x1, p->x1);
y1 = MAX(y1, p->y1);
}
};
class IRect
{
private :
int x0, y0, x1, y1;
public :
IRect(int a, int b, int c, int d) : x0(a), y0(b), x1(c), y1(d)
{}
operator DRect() const
{
return DRect(x0, y0, x1, y1);
}
operator DRect*() const
{
return &DRect(x0, y0, x1, y1);
}
};
and the execution code here.
void main()
{
DRect d(5.3, 5.3, 15.6, 15.6);
IRect i(10, 10, 100, 100);
/* 1. No problem with compiling this code. */
d.Union(&(static_cast<DRect>(i)));
/* 2. It isn't compiled. */
d.Union(&i);
}
Use references instead, pointers should normally not be used unless
you have to.
#include <iostream>
class DRect {
private :
double x0, y0, x1, y1;
public :
DRect(double a, double b, double c, double d)
: x0(a), y0(b), x1(c), y1(d) {}
void Union(const DRect& p) {
std::cout << "Union";
}
};
class IRect {
private :
int x0, y0, x1, y1;
public :
IRect(int a, int b, int c, int d)
: x0(a), y0(b), x1(c), y1(d) {}
operator DRect() const {
return DRect(x0, y0, x1, y1);
}
};
int main() { // Notice int and not void as return-type
DRect d(5.3, 5.3, 15.6, 15.6);
IRect i(10, 10, 100, 100);
d.Union(i);
}
--
Erik Wikstr=F6m