Implicit cast through constructor with multiple arguments
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?
In a word, no. The most succinct option is MyClass(15,8) + m;
.
No, but you can construct in place:
MyClass m;
m + MyClass(15,8);
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.
精彩评论