运算符=与转换运算符结合时的歧义
operator= ambiguity in junction with conversion operators
我有以下情况:
class B;
class A {
private:
int n;
public:
A& operator=(const A& a) {
}
A& operator=(const int n) {
this->n = n;
}
friend class B;
};
class B {
private:
A a;
public:
operator A&() {
return a;
}
operator int&() {
return a.n;
}
};
当我执行这个代码时:
A a;
B b;
int i = b;
a = b;
a = i;
我有以下错误:
error C2593: 'operator =' is ambiguous
..CrossPPTestTestProxy.cpp(40): could be 'A &A::operator =(const int)'
..CrossPPTestTestProxy.cpp(37): or 'A &A::operator =(const A &)'
while trying to match the argument list '(A, B)'
假设我不能将
A& operator =(const B&)
添加到A类中,如何解决这种歧义。我必须这样做的原因很复杂,但如果这样的事情能奏效,那就太好了。
可能有一些优先级或类似于明确的运算符关键字的东西。。。如有任何建议,我们将不胜感激。
更新:任何类型的强制转换都不能在代码的第二部分中使用。问题是找到一个只修改第一个代码部分的解决方案。
再更新一次:代码部分#2必须按原样编译。
这看起来像是多态性的作业:
class B;
class A {
int n;
public:
A& operator=(const A& a) {...}
A& operator=(const int n) {
this->n = n;
return *this;
}
friend class B;
};
class B : public A {
A a;
public:
operator int&() {
return a.n;
}
};
int main() {
A a;
B b;
int i = b; // works
a = b; // works
a = i;
}
演示
您提出的方式使问题基本上无法解决。
显然有两种方式可以从B
分配给A
,但都不是优选的。
唯一的解决方案(不涉及类)是显式强制转换,这样就可以强制进行转换。
通常,赋值和转换是多余的:如果您允许隐式转换(使用U::operator T() const
到-或使用T::T(const U&)
从-),则不必提供默认值以外的赋值;如果您想要隐式异构赋值,则必须不提供转换,或者最多将其设为explicit
。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 消除好友和成员二进制运算符的歧义
- 如何在模板化转换运算符中消除此构造的歧义?
- C++ 类的构造函数和函数调用运算符 () 重载之间的歧义
- 通过继承重载运算符会导致歧义
- 运算符的歧义错误<<自定义 std::ostream 子类中的重载
- 将文本文件数据读入字符数组时提取运算符的歧义
- 转换运算符重载歧义,编译器不同
- 模板运算符似乎因歧义而失败
- 嵌套类中对运算符[]的调用存在歧义
- C++重载I/O运算符:克服歧义
- 与 [] 运算符和多重继承的歧义
- C++ "std::cin >>"中的"运算符>>"的歧义
- g++和clang++-删除由重载转换运算符歧义获取的指针
- 在C++中重载运算符时,如何防止整数歧义
- 运算符() 重载和函数对象中的 c'tor 歧义
- 运算符=与转换运算符结合时的歧义
- 转换运算符重载 - 函数歧义
- 重载运算符 == 和 != :编译器抱怨歧义