C++类型转换运算符
C++ type conversion operator
我正在研究运算符重载,有些部分很难理解。
请参阅此示例代码。
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;
}
};
如您的示例a
未const
,双转换是最佳匹配。如果修复此问题,则会获得预期的输出。
现场示例
。一些基于意见的PS:
我没有找到核心准则对转换运算符的看法,但是如果我必须为转换运算符制定一个准则,那就是:避免使用它们。如果使用它们,请使它们explicit
。到目前为止,隐性转换的惊人效果远远超过了好处。
举个例子,考虑std::bitset
.它没有提供转换运算符,而是to_string
、to_ulong
和to_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;
}
相关文章:
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 自定义类型转换运算符在转发引用上调用时不起作用(当对象按值传递时有效)
- 模板化隐式类型转换运算符
- 具有重载类型转换运算符的函数对象崩溃
- 类型转换运算符重载与 as 非成员函数
- 从类模板中排除转换运算符...<类型名 T>基于 T 上的特征
- 初始化中的模板转换运算符类型推导规则是什么?
- C++运算符== 和用户定义的类型转换
- C++类型转换运算符
- C++11 何时相对于运算符优先级进行算术类型转换
- 在unordered_map中,C2440"类型转换":无法转换...定义运算符 == 和hash_value时
- 模板类自动类型转换的运算符重载
- clang和gcc中的模板转换运算符类型推导不同
- C++:重载运算符.奇怪的类型转换运算符
- 二元运算符重载,隐式类型转换
- 将运算符类型转换为除某些引用之外的任何算术类型
- 通过具有重载运算符函数的构造函数自动进行类型转换
- ostream&运算符<<中的类型转换
- 类型转换为类型&&运算符
- VS 2012中的条件运算符类型转换