如何最有效地从重载运算符返回多个值? (C++)
我有一个“复合体”类,其中包含实值和虚值。我正在尝试重载 + 运算符,以便我可以将实数添加到实数,将虚数添加到虚数,但我在这里用头撞墙。
在函数中,我可以轻松获取值。然而,归还它们是一个婊子。
我的计划是也重载“=”运算符,这样我就可以
复杂化 a、b、c;
(设置a和b)
c = a + b;
然后让 a+b 返回一个复数,然后让复数 c 等于 a+b 返回的复数
关于这是否是一条可行的路径有什么意见吗?
关于是否可以做得更容易有什么意见吗?
I have a class "complex" that contains a Real and an Imaginary value. I'm trying to overload the + operator so I can add real to real and imaginary to imaginary, but I'm banging my head against a wall here.
In the function, I can get the values easy. Returning them however, is a bitch.
My plan is to overload the '=' operator, too, so I can go
complex a, b, c;
(set a and b)
c = a + b;
then have a+b return a complex, then have complex c equal the complex returned by a+b
Any opinion on whether that's a viable path?
Any opinion on whether it can be done easier?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将它们作为
复杂
返回!例如,您不需要重载
operator=
;编译器将为您生成一个执行逐个元素复制的文件,这对于复杂的类来说可能就足够了。Return them as a
complex
! e.g.You shouldn't need to overload
operator=
; the compiler will generate one for you that does an element-by-element copy, which will probably suffice for a complex class.我不确定我是否理解这个问题。你有一个
复杂
类吗?当然,这只是一个练习;我们有
std::complex
。I'm not sure I understand the problem. Do you have a
complex
class?This is, of course, just an exercise; we have
std::complex
.重载 + 运算符有什么问题:
运算符 =() 也类似吗? (但是编译器默认给你这个)
What's wrong with overloading the + operator:
And the operator=() similarly? (but the compiler give you this by default)
它是可行的,但标准库中已经有 complex 类。重用它或者至少看看操作符重载是如何完成的。
It is viable but there is already complex class in standard library. Reuse it or at least have a look how the operator overloading is done there.