C++类型转换运算符

C++ type conversion operator

本文关键字:运算符 类型转换 C++      更新时间:2023-10-16

我正在研究运算符重载,有些部分很难理解。

请参阅此示例代码。

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("%cn", b);
printf("%dn", c);
printf("%fn", 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

为什么转换为字符和整数时调用双运算符?

祝你有美好的一天!:)

您忘记了double转换运算符上的const

operator double() const {  // <---------------------------
cout << "operator double() called" << endl;
return this->c;
}
};

如您的示例aconst,双转换是最佳匹配。如果修复此问题,则会获得预期的输出。

现场示例

。一些基于意见的PS:

我没有找到核心准则对转换运算符的看法,但是如果我必须为转换运算符制定一个准则,那就是:避免使用它们。如果使用它们,请使它们explicit。到目前为止,隐性转换的惊人效果远远超过了好处。

举个例子,考虑std::bitset.它没有提供转换运算符,而是to_stringto_ulongto_ullong。最好是显式代码。A a; double d = a;有点神秘。我必须查看类定义才能了解真正发生的事情。另一方面,A a; double d = a.as_double();可以做完全相同的事情,但更具表现力。

是的,所以问题是,你让除了双运算符之外的所有运算符都 const。我仍然有点惊讶,因为这个 const 只是意味着运算符调用不会修改类成员。似乎所有 3 个都只调用双运算符。我会让所有 3 个操作都做常量,然后它会正常工作。

如果有人解释为什么会发生这种情况,我也想知道。 干杯。

operator char() const { // here is const
cout << "operator char() called" << endl;
return this->a;
}
operator int() const { // here is const
cout << "operator int() called" << endl;
return this->b;
}
operator double() { // here is no const
cout << "operator double() called" << endl;
return this->c;
}