I am studying operator overloading, there are some parts that are difficult to understand.
See this example code.
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;
}
Run Code Online (Sandbox Code Playgroud)
I made this code to test for type conversion operator and expected that the appropriate function would be called for each type of data.
But the result is..
operator double() called
operator double() called
operator double() called
<-- strange character is gone on board!
1
1.618000
Run Code Online (Sandbox Code Playgroud)
I can not understand why the results are not as follows.
operator char() called
operator int() called
operator double() called
a
99
1.618
Run Code Online (Sandbox Code Playgroud)
Why is double operator called when converting to char and int?
Have a good day! :)
你忘了const在double转换操作符:
operator double() const { // <---------------------------
cout << "operator double() called" << endl;
return this->c;
}
};
Run Code Online (Sandbox Code Playgroud)
在您的示例a中,不是const,双重转换是最佳匹配。如果修复,则将获得预期的输出。
...一些基于意见的PS:
我没有找到有关转换运算符的核心准则,但是如果我必须为转换运算符制定一个准则,那就是:避免使用它们。如果使用它们,请制造它们explicit。隐式转换的令人惊讶的影响远远超过了收益。
仅作为示例,请考虑std::bitset。相反,提供转换操作符有to_string,to_ulong和to_ullong。最好让您的代码明确。A a; double d = a;有点神秘。我必须查看类定义才能真正了解发生了什么。另一方面,它A a; double d = a.as_double();可以做完全相同的事情,但是更具表现力。
| 归档时间: |
|
| 查看次数: |
258 次 |
| 最近记录: |