kai*_*ong 2 c++ g++ llvm ambiguous
当存在某个构造函数时,我的代码不明确。但是,当我注释掉所述构造函数时,编译器会抱怨缺少必要的构造函数。
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;
}
Run Code Online (Sandbox Code Playgroud)
位置 1被注释掉后,位置 2就会抛出错误。
如果包含位置 1,则存在歧义错误。
基本上,我想删除位置 1并通过 double->E->X 来投射 double->X。
出现歧义是因为(在行中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; }
};
Run Code Online (Sandbox Code Playgroud)