【发布时间】:2019-05-16 18:49:40
【问题描述】:
我在 foo 类中编写了隐式转换运算符到 double 和显式转换运算符到 int,以及将 int 作为参数的函数。尽管被调用并没有强制转换 foo 对象代码被执行。
我使用 gcc PRETTY_FUNCTION 发现 foo 对象被强制转换为 double 然后转换为 int。
class foo
{
public:
int x, y;
foo(int x, int y) : x{x}, y{y} {}
explicit operator int() {cout << __PRETTY_FUNCTION__ << "\n"; return x/y;}
operator double() {cout << __PRETTY_FUNCTION__ << "\n"; return double(x)/double(y);}
};
void printint(int x)
{
cout << x << "\n";
}
int main()
{
foo var(1,2);
printint(var);
}
我希望这不会因为显式运算符而编译,但它会编译并将 0 打印为 int(1/2)。
程序的输出是: foo::operator double() 0
【问题讨论】:
-
那么如果类对象可以隐式转换为某物然后转换为int,那么显式运算符是什么意思,难道不应该阻止它的发生吗?
标签: c++