C++两个双精度重载运算符%
是否可以为两个双精度重载operator%
?
const double operator%(const double& lhs, const double& rhs)
{
return fmod(lhs, rhs);
}
当然,这会产生错误,因为两个参数之一必须具有类类型。 所以我考虑利用 C++ 隐式构造函数调用的可能性来解决这个问题。我按照以下方式做到了:
class MyDouble {
public:
MyDouble(double val) : val_(val) {}
~MyDouble() {}
double val() const { return val_; }
private:
double val_;
};
const double operator%(const MyDouble& lhs, const double& rhs)
{
return fmod(lhs.val(), rhs);
}
const double operator%(const double& lhs, const MyDouble& rhs)
{
return fmod(lhs, rhs.val());
}
...并且:
double a = 15.3;
double b = 6.7;
double res = a % b; // hopefully calling operator%(const MyDouble&, const double) using a implicit constructor call
不幸的是,这不起作用!任何提示、想法……都将受到赞赏! 提前致谢, 乔纳斯
is it possible to overload the operator%
for two doubles?
const double operator%(const double& lhs, const double& rhs)
{
return fmod(lhs, rhs);
}
Of course, this generates an error because one of the two parameters must have a class type.
So I thought about utilizing the possibility of implicit constructor calls of C++ to get around of this problem. I did it in the following way:
class MyDouble {
public:
MyDouble(double val) : val_(val) {}
~MyDouble() {}
double val() const { return val_; }
private:
double val_;
};
const double operator%(const MyDouble& lhs, const double& rhs)
{
return fmod(lhs.val(), rhs);
}
const double operator%(const double& lhs, const MyDouble& rhs)
{
return fmod(lhs, rhs.val());
}
... and:
double a = 15.3;
double b = 6.7;
double res = a % b; // hopefully calling operator%(const MyDouble&, const double) using a implicit constructor call
Unfortunately, this does not work! Any hints, ideas, ... are appreciated!
Thanks in advance,
Jonas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不起作用的原因是,只有当表达式的至少一个操作数具有类或枚举类型时,才会触发用户定义的运算符函数的重载解析。
所以你运气不好。这行不通。
我认为您可以尝试的最好方法是等待 C++0x 编译器,而不是编写
3.14
,而是编写3.14_myd
,作为用户定义的文字。The reason this doesn't work is because overload resolution for user defined operator functions is only triggered if at least one operand of the expression has a class or enumeration type.
So you are out of luck. This won't work.
I think the best you could try is waiting for a C++0x compiler and instead of writing
3.14
, you write3.14_myd
, as a user defined literal.或者,实现 double MyDouble::operator%(const double&) const;,如下所示:
alternatively, implement
double MyDouble::operator%(const double&) const;
, like so: