我正在研究运算符重载,有些部分很难理解。
请参阅此示例代码。
class A {
private:
char a;
int b;
double c;
public:
A(char _a = 'a', int _b = 99, double _c = 1.618) :a(_a), b(_b), c(_c){
}
public:
operator char() const {
cout << "operator char() called" << endl;
return this->a;
}
operator int() const {
cout << "operator int() called" << endl;
return this->b;
}
operator double() {
cout << "operator double() called" << endl;
return this->c;
}
};
int main(void) {
A a;
char b = a;
int c = a;
double d = a;
printf("%c\n", b);
printf("%d\n", c);
printf("%f\n", d);
return 0;
}
我编写这段代码是为了测试类型转换运算符,并希望为每种数据类型调用适当的函数。
但结果是..
operator double() called
operator double() called
operator double() called
<-- strange character is gone on board!
1
1.618000
我无法理解为什么结果不是如下所示。
operator char() called
operator int() called
operator double() called
a
99
1.618
为什么转char和int时会调用double运算符?
祝你有个美好的一天! :)
最佳答案
您忘记了 double
转换运算符上的 const
:
operator double() const { // <---------------------------
cout << "operator double() called" << endl;
return this->c;
}
};
在您的示例中 a
不是 const
,双重转换是最佳匹配。如果您修复该问题,您将获得预期的输出。
...一些基于意见的 PS:
我没有找到关于转换运算符的核心指南,但如果我必须为转换运算符制定一个指南,那就是:避免使用它们。如果您使用它们,请将它们设为显式
。隐式转换的惊人效果远远超过了好处。
举个例子,考虑 std::bitset
.它没有提供转换运算符,而是提供了 to_string
、to_ulong
和 to_ullong
。最好让您的代码明确。 一个; double d = a;
有点神秘。我将不得不查看类定义以了解真正发生的事情。另一方面 A a; double d = a.as_double();
可以做完全相同的事情,但表现力更强。
关于C++ 类型转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55147007/