the workshop is to take the result of x / y
and display it as double
. so if I were to display it by line like
std::cout << (double)A
assuming x
is 3 and y
is 2 the value should display as 1.5
.
For that particular example, you should define a custom operator<<
, eg:
std::ostream& operator<<(std::ostream &out, const object &value)
{
out << (double) value;
return out;
}
Then you can pass the object
directly to cout
(or any other ostream
descendant):
std::cout << A;
I am not sure how to make the definition of this, what I have is something like this
Object::operator double() {
double dbl = 0;
dbl = this->x / this->y
return dbl;
}
What you have is fine, as far as declaring a conversion operator. Though you should declare it as const
, at least, since it does not modify any members of object
. Just be sure to watch out for y=0
, since divide by 0 is an error. And note that you are performing integer division instead of floating-point division, so you need to cast one of the values to double
before dividing.
Now this is obviously wrong because my x
and y
values are random and not obtaining the values of the object A
.
If you are getting random results, it means your input is random to begin with (ie, you are likely not initializing your x
and y
variables). In the object
declaration you have shown, x
and y
are private, and you don't provide any constructor or setter method(s) to set their values.
Try something more like this instead:
class object {
int x;
int y;
public:
object();
object(int aX, int aY);
int getX() const;
void setX(int value);
int getY() const;
void setY(int value);
operator double() const;
};
std::ostream& operator<<(std::ostream &out, const object &value);
#include <limits>
object::object()
: x(0), y(0)
{
}
object::object(int aX, int aY)
: x(aX), y(aY)
{
}
int object::getX() const
{
return x;
}
void object::setX(int value)
{
x = value;
}
int object::getY() const
{
return y;
}
void object::setY(int value)
{
y = value;
}
object::operator double() const
{
if (y != 0)
return (double)x / (double)y;
return std::numeric_limits<double>::quiet_NaN();
}
std::ostream& operator<<(std::ostream &out, const object &value)
{
out << (double) value;
return out;
}
Then you can do things like this:
object A(3, 2);
std::cout << A;
object A;
A.setX(3);
A.setY(2);
std::cout << A;