通过具有多个参数的构造函数进行隐式转换
如果我有 MyClass
这两个构造函数:
MyClass(int n1);
MyClass(int n1, int n2);
和一个重载的(非成员)operator+
:
MyClass operator+(MyClass m1, const MyClass& m2);
这使我能够编写如下代码:
MyClass m;
5 + m:
我猜它使用了隐式强制转换定义的构造函数,对吗?
有什么方法可以使用带有 2 个参数的构造函数来执行此隐式转换吗?代码看起来像这样:
MyClass m;
{15, 8} + m:
?
或者也许只是从 {9, 4} 显式转换为 MyClass
对象?
If I have these 2 constructors for MyClass
:
MyClass(int n1);
MyClass(int n1, int n2);
and an overloaded (non-member) operator+
:
MyClass operator+(MyClass m1, const MyClass& m2);
This enables me to write code like this:
MyClass m;
5 + m:
which I guess uses an implicit cast through the defined constructor, correct?
Is there any way to do this implicit cast with the constructor taking 2 arguments? With code looking something like this:
MyClass m;
{15, 8} + m:
?
Or maybe just do an explicit cast from {9, 4} to a MyClass
object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一句话,不。最简洁的选项是
MyClass(15,8) + m;
。In a word, no. The most succinct option is
MyClass(15,8) + m;
.不,但您可以就地构建:
No, but you can construct in place:
我不这么认为,但为什么你需要它是隐式的而不是显式的?如果您无论如何都必须使用括号表示法,那么它不是可以从单个变量生成的东西,所以我认为简单地说:
myclass(15, 8) + m 没有任何缺点;
这将在堆栈上生成它,并产生与隐式转换相同的结果。
I don't believe so, but why do you need it to be implicit rather than explicit? If you're going to have to use the bracket notation anyway, it's not something that could be generated from a single variable, so I don't believe there's any downside to simply saying:
myclass(15, 8) + m;
This will generate it on the stack, and produce the same result as an implicit cast.