描述
當存在某個建構式時,我的代碼不明確。但是,當我注釋掉所說的建構式時,編譯器會抱怨缺少必要的建構式。
最小作業示例
struct X;
struct E{
E(const double& r){ /* important protocol stuff */ }
E(const X&);
};
struct X{
X(){ /* important init stuff */ }
~X(){ /* important delete stuff */ }
//X(const double& r){ *this=E(r); } // POSITION 1
X(const X& x){ /* important init stuff */ *this=x; }
X(const E& e){ /* important init stuff */ *this=e; }
const X& operator=(const X& x){ return *this=E(x); }
const X& operator=(const E& e){ /* important stuff */ return *this; }
};
E::E(const X& x){ /* important protocol stuff */ }
E operator (const E& x, const E& y){ /* important protocol stuff */ return E(1); }
E operator*(const E& x, const E& y){ /* important protocol stuff */ return E(2); }
int main(){
X x,y;
x = 3.0;
X u = 4.0; // POSITION 2
y = x u * 5.0;
X z = 6.0 7.0 * y;
}
注釋掉位置 1后,位置 2將引發錯誤。
包含位置 1時,存在歧義錯誤。
基本上,我想洗掉位置 1并通過 double->E->X 投射 double->X。
問題
- 問題的名稱是什么?
- 我如何解決它?
我嘗試過的事情:
- 各種建構式前面的顯式關鍵字。對于 E,這會導致位置 2之后 出現錯誤。對于 X,這會導致與注釋掉位置 1相同的錯誤。
- 從 X,E 的定義中洗掉建構式/運算子。然而,這不是解決方案,因為我需要能夠包含一些重要的東西。
- 嘗試不同的編譯器(g 8.3.0 和 9.2.0,clang 12.0.0)。這并沒有改變問題。
uj5u.com熱心網友回復:
出現歧義是因為(x = 3.0;在行中)編譯器無法決定使用兩個賦值運算子中的哪一個:帶有X&引數的還是帶有 的E&,因為兩種引數型別都可以從給定的型別轉換double(因為兩者E都有X建構式帶一個const double&引數)。
您可以通過提供第三個賦值運算子來解決此錯誤,該運算子帶有一個const double&引數,如下所示:
struct X {
X() { /* important init stuff */ }
~X() { /* important delete stuff */ }
X(const double& r){ *this=E(r); } // Now uncommented (required)
X(const X& x) { /* important init stuff */ *this = x; }
X(const E& e) { /* important init stuff */ *this = e; }
const X& operator=(const double& x) { return *this = E(x); } // Add this!
const X& operator=(const X& x) { return *this = E(x); }
const X& operator=(const E& e) { /* important stuff */ return *this; }
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537145.html
標籤:C 克 LLVM模糊的
上一篇:如何完美轉發多個struct成員
