C++ 类型转换运算符

标签 c++ types casting

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

请参阅此示例代码。

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,双重转换是最佳匹配。如果您修复该问题,您将获得预期的输出。

Live example

...一些基于意见的 PS:

我没有找到关于转换运算符的核心指南,但如果我必须为转换运算符制定一个指南,那就是:避免使用它们。如果您使用它们,请将它们设为显式。隐式转换的惊人效果远远超过了好处。

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

关于C++ 类型转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55147007/

相关文章:

javascript - 如何在 Typescript 中从 request.body 检查对象类型?

casting - 为什么不能在 F# 中添加 int 和 float 文字?

c++ - 从命令提示符编译 BADA 应用程序

c++ - 如何将局部引用变量传递给 lambda 函数,但该函数将在其关闭已经完成时被调用?

python - 如何检测子列表中的逻辑和字符串索引并将其删除

c - 如果 "long"和 "int"在平台上的大小相同 - "long"和 "int"有什么不同吗?

java - 如何转换 hashmap.values().toArray() ,其中这些 value() 也是 HashMap ?

java - 将方法参数传递给java中byte,int,int类型的方法参数

c++ - 在 C++ 中使用二维 vector 时出错

c++ - TCHAR* envp[] : What is it?