三种可能的情况
1.类中构造函数与重载转换运算符间的二义性,如下所示:
class B; class A { public: A(const B& b) { cout << "A()" << endl; } private: int data; }; class B { public: B():data(0) {} operator A() const; private: int data; }; void ff(const A& a) { cout << "ff" << endl; } int main() { B b; ff(b); //错误,会产生二义性 system("pause"); return 0; }
产生二义性的原因是因为有两种方法来实现由B转换为A,一种方法是调用类A的构造函数,另一种是调用类B里自定义的转换运算符。这两个途径都一样可行,所以编译器拒绝从他们中选择一个。
2. 函数调用中也存在二义性
void ff(int a) { cout << "ff(int)" << endl; } void ff(char a) { cout << "ff(char)" << endl; } int main() { double a = 10.0; ff(a); //错误。二义性。要想调用,需ff(static_cast<int>(a)); return 0; }
该函数调用的二义性来源于C++语言的标准转换。a转换成int和char都可以,所以编译器不会通过。
3.多继承中存在的二义性
class Base1 { public: void dolt(void) { cout << "Base1::dolt()" << endl; } }; class Base2 { public: void dolt(void) { cout << "Base2::dolt()" << endl; } }; class Derived : public Base1, public Base2 { }; int main() { Derived a; a.dolt(); //错误,二义性。要想成功调用,需指明函数所在的基类,如//a.Base1::dolt(); return 0; }