构造时从原语到用户定义的分配
抱歉,标题模糊,我似乎错过了一些东西。
我很犹豫要不要发布这个,因为它看起来很基本,但我无法让它发挥作用。我的 IDE 告诉我以下内容是错误的。我有一个名为 IRatio 的类,我希望它可以与 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;
};
现在我知道以下几行可以工作:
IRatio n1(0.01f);
IRatio n2;
n2 = 0.02f;
但是,令我完全惊讶的是,这一行不起作用:
IRatio n3 = 0.03f;
我如何让它工作?我假设在这种情况下调用了复制构造函数?或者即使是赋值运算符,我也不介意!我知道 std::string 可以做到这一点。
std::string s = "hello!";
谢谢
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 following 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码应该按原样工作。也就是说,IRatio 本身不管理任何资源,因此您不需要复制构造函数和赋值运算符。这应该做:
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:你的代码应该可以工作。但是,
0.03f
的类型为float
。您想说0.03L
来表示long double
。但这在这里不一定重要,float
可以转换为long double
。是的,带有参数 const long double& 的构造函数将用于创建一个临时的
IRatio
对象,该对象将被复制到n3
(以及您的编译器应该优化副本,因此您可能不会在这里看到复制构造函数调用,除非您告诉它不要优化)。Your code should work. However,
0.03f
is of typefloat
. You want to say0.03L
to saylong double
. But this doesn't necessarily matter here,float
is convertible tolong double
.Yes, the constructor with parameter
const long double&
would be used to create a temporaryIRatio
object, which would be copied ton3
(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).