簡體   English   中英

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("%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:

我沒有找到關於轉換運算符的核心指導原則,但如果我必須為轉換運算符編制指南,那就是:避免使用它們。 如果您使用它們,請explicit它們。 隱式轉換的驚人效果遠遠超過了它的好處。

舉個例子,考慮一下std::bitset 它不是提供轉換運算符,而是具有to_stringto_ulongto_ullong 最好將代碼顯式化。 A a; double d = a; 有點神秘。 我必須查看類定義以了解實際情況。 另一方面A a; double d = a.as_double(); A a; double d = a.as_double(); 可以做同樣的事情,但更具表現力。

是的問題是,除了double運算符之外,你使所有運算符都為const。 我仍然有點驚訝,因為這個const只意味着操作符調用不會修改類成員。 似乎只有雙重運算符被調用所有3.我將所有3個運算符構成const然后它將正常工作。

如果有人解釋為什么會這樣,我也想知道。 干杯。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM