假定以下代碼:爲什麼我不能在比較中使用演員操作?
#include <string>
#include <iostream>
using namespace std;
struct A
{
operator int()
{
return 123;
}
operator string()
{
return string("abc");
}
};
void main()
{
A a;
cout<<(a==123)<<endl;
//cout<<(a==string("abc"))<<endl;
}
首先,我比較對象a
與int
變量。然後,我試圖將它與一個string
變量進行比較,但要編譯的程序文件。通過包含比較註釋的行,它編譯得很好。問題是什麼?
你得到一個編譯錯誤?它說什麼?有沒有告訴你什麼?也許,這些參數類型沒有可用的'=='運算符重載? –
嘗試使這些運算符'const'正確,以便您可以將它們用於'const A object;'。例如'operator int()const {...}'。 – iammilind