![](/img/trans.png)
[英]Ternary operator applied to class with conversion operator and delete constructor causes ambiguity
[英]ambiguity with conversion operator and constructor
我正在學習 C++,遇到了轉換運算符的問題。 我正在創建一個可以對復數進行基本操作的復雜類。
class complex
{
double real, img;
public:
complex(double re=0,double im=0){
real = re;
img = im;
}
double get_real() const{
return real;
}
double get_img() const{
return img;
}
};
我重載了 + 運算符:
complex operator+(complex a,complex b){
return complex(a.get_real()+b.get_real(),a.get_img()+b.get_img());
}
由於構造函數的原因,使用帶有復數的雙精度/整數添加此代碼可以正常工作。
complex a(2,4);
complex b = 1+a;
但是當我在類中使用轉換運算符時
operator int(){
int re = real;
return re;
}
加法雙/整數彎腰工作
b = 1 + a;
// ambiguous overload
這看起來很奇怪,誰能解釋一下添加轉換運算符是如何造成這種歧義的?
我在網上找不到任何資源。
在這個表達式語句中
b = 1 + a;
可以使用轉換構造函數將操作數1
轉換為 complex 類型,或者可以使用轉換運算符將對象 a 轉換為 int 類型。
所以兩個二元運算符 + 之間存在歧義:要么可以使用 int 類型的內置運算符,要么可以使用類型 complex 的用戶定義運算符。
為避免歧義,您可以例如將轉換運算符聲明為顯式。
explicit operator int() const {
int re = real;
return re;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.