Primitive to user defined assignment on construction
Sorry for the blurry title, I seem to be missing something.
I was hesitant to post this, because it seems so basic, but I can't get it to work. My IDE tells me the fo开发者_运维技巧llowing is incorrect. I have a class called IRatio which I want to be interchangeable with long double.
class
IRatio
{
protected:
long double
mValue;
public:
IRatio();
IRatio(
const IRatio& ir);
IRatio(
const long double& ld);
IRatio&
operator=(
const IRatio& ir);
IRatio&
operator=(
const long double& ld);
operator long double() const;
};
Now I know that the following lines work:
IRatio n1(0.01f);
IRatio n2;
n2 = 0.02f;
However, to my complete suprise, this line doesn't work:
IRatio n3 = 0.03f;
How do I get this to work? I assumed the copy constructor was called in this case? Or even if it was the assignment operator, I don't mind! I know that std::string can do it.
std::string s = "hello!";
Thanks
Your code should work as is. That said, IRatio
doesn't manage any resources on its own, so you don't need the copy constructor and assignment operator. This should do:
struct IRatio {
IRatio() : d(0L) { }
IRatio(long double d) : d(d) { }
operator long double() const { return d; }
private:
long double d;
};
int main(int argc, char* argv[])
{
IRatio r = 0.02f;
return 0;
}
Your code should work. However, 0.03f
is of type float
. You want to say 0.03L
to say long double
. But this doesn't necessarily matter here, float
is convertible to long double
.
Yes, the constructor with parameter const long double&
would be used to create a temporary IRatio
object, which would be copied to n3
(and your compiler should optimizes the copy, so you are likely not to see a copy constructor call here, unless you have told it not to optimize).
精彩评论