通过具有多个参数的构造函数进行隐式转换

发布于 2024-09-25 07:38:32 字数 494 浏览 0 评论 0原文

如果我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

云朵有点甜 2024-10-02 07:38:32

一句话,不。最简洁的选项是MyClass(15,8) + m;

In a word, no. The most succinct option is MyClass(15,8) + m;.

夜无邪 2024-10-02 07:38:32

不,但您可以就地构建:

MyClass m;
m + MyClass(15,8);

No, but you can construct in place:

MyClass m;
m + MyClass(15,8);
人间☆小暴躁 2024-10-02 07:38:32

我不这么认为,但为什么你需要它是隐式的而不是显式的?如果您无论如何都必须使用括号表示法,那么它不是可以从单个变量生成的东西,所以我认为简单地说:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文