cli/c++增量运算符重载
我有一个关于 cli/c++ 环境中运算符重载的问题
static Length^ operator++(Length^ len)
{
Length^ temp = gcnew Length(len->feet, len->inches);
++temp->inches;
temp->feet += temp->inches/temp->inchesPerFoot;
temp->inches %= temp->inchesPerFoot;
return temp;
}
(代码来自 ivor horton 的书)。
为什么我们需要在堆上声明一个新的类对象(temp)才能返回它? 我在谷歌上搜索了有关超载的信息,但实际上没有太多信息,我感觉有点迷失。
i have a question regarding operator overloading in cli/c++ environment
static Length^ operator++(Length^ len)
{
Length^ temp = gcnew Length(len->feet, len->inches);
++temp->inches;
temp->feet += temp->inches/temp->inchesPerFoot;
temp->inches %= temp->inchesPerFoot;
return temp;
}
(the code is from ivor horton's book.)
why do we need to declare a new class object (temp) on the heap just to return it?
ive googled for the info on overloading but theres really not much out there and i feel kinda lost.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是 .NET 中实现运算符重载的方式。重载运算符是静态函数,它返回一个新实例,而不是更改当前实例。因此,post 和 prefix ++ 运算符是相同的。大多数有关运算符重载的信息都涉及本机 C++。您可以查看 .NET 特定信息,查找 C# 示例,例如: http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx
.NET GC 允许创建大量轻量级新实例,这些实例会自动收集。这就是 .NET 重载运算符比本机 C++ 更简单的原因。
This is the way operator overloading is implemented in .NET. Overloaded operator is static function, which returns a new instance, instead of changing the current instance. Therefore, post and prefix ++ operators are the same. Most information about operator overloading talks about native C++. You can see .NET specific information, looking for C# samples, for example this: http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx
.NET GC allows to create a lot of lightweight new instances, which are collected automatically. This is why .NET overloaded operators are more simple than in native C++.
是的,因为您在这里重载了 POST-增量运算符。因此,尽管新值存在,但原始值可能会在代码中大量使用、复制并存储在其他地方。示例:
虽然
len
会增加,但原始值可能会被函数存储在其他地方。这意味着您可能同时需要两个不同的值。因此创造并返回了新价值。Yes, because you're overloading POST-increment operator here. Hence, the original value may be used a lot in the code, copied and stored somewhere else, despite the existance of the new value. Example:
While
len
will be increased, the original value might be stored by the function somewhere else. That means that you might need two different values at the same time. Hence the creation and return of a new value.