Re: floating point number wrapper
On Jun 3, 6:00 am, "Hicham Mouline" <hic...@mouline.org> wrote:
hello,
I am trying to define a double wrapper that wraps only >=0.0 doubles,
class double_constant_wrapper {
public:
explicit spot_rate_constant(double r);
double operator()() const;
double& operator=(double r);
private:
double r_;
};
inline double_constant_wrapper::double_constant_wrapper(double r)
: r_(r)
{
if (r<0.0)
throw exception("number cannot be <0");
}
inline double double_constant_wrapper::operator() const
{
return r_;
}
inline double& double_constant_wrapper::operator=(double r)
{
return r_=r;
}
If the user attempts to construct a double_constant_wrapper with a <0.0
double, she will get an exception.
Do the members signatures seem ok?
No, the corrected compilable version is below. ;)
#include <stdexcept>
#include <iostream>
#include <ostream>
class double_constant_wrapper {
public:
explicit double_constant_wrapper(double r);
double operator()() const;
double& operator=(double r);
private:
double r_;
};
inline double_constant_wrapper::double_constant_wrapper(double r)
: r_(r)
{
if (r<0.0)
throw std::runtime_error("number cannot be <0");
}
inline double double_constant_wrapper::operator()() const
{
return r_;
}
inline double& double_constant_wrapper::operator=(double r)
{
return r_=r;
}
int
main()
{
double_constant_wrapper r(0);
(r=1)=-1;
std::cout << r() << std::endl;
}
And this demonstrates that returning double& in operator=() isn't a
very bright idea with respect to maintaining the class invariant
(r_>=0).
--
Regards,
Alex
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]