使用许多类型转换器操作员过载时的模糊过载 [英] Ambiguous overload when using many typecasts operator overloads
问题描述
我想为字符串创建一个wrapperClass。我还希望类能够返回wrapperClass的地址和存储(包装)字符串的地址:
I want to create a wrapperClass for strings. I also want the class to be able to return the address of the wrapperClass and the address of the stored (wrapped) string:
void FunctionString(string*);
void FunctionWrappedString(wrappedString*);
int main(){
wrappedString wrappedStringObject;
FunctionString(&wrappedStringObject);
FunctionWrappedString(&wrappedStringObject);
wrappedString anotherWrappedStringObject;
if(wrappedStringObject == anotherWrappedStringObject){
// code
}
}
以下是类的重要部分:
class wrappedString{
typedef char* string;
string storedString;
operator string*(){
// some code
return &storedString;
}
operator wrapperString*(){
// some code
return this;
}
operator string(){
// some code
return storedString;
}
}
但是,当我使用比较运算符时,这些失败:
However these fail when I use the comparison operator:
if(wrappedStringObject == anotherWrappedStringObject){
// code
}
表示候选者是:operator ==(string,string)and operator = =(string *,string *)
Saying that the candidates are: operator==(string,string) and operator==(string*,string*)
推荐答案
多个隐式转换运算符导致此问题。如果目标是让包装的 string
对象的行为像 string
(实际上是 char *
?!?),那么只允许一个隐式转换运算符,而保留 explicit
,以减少错误行为的风险。这只适用于C ++ 11,但你现在应该使用它:
Multiple implicit cast operators are causing this problem. If the goal is to have the wrapped string
object behave like a string
(which is actually a char*
?!?), then only allow one implicit cast operator, while leaving the rest explicit
to reduce the risk of misbehavior. This only works on C++11, but you should be using that by now anyway:
class wrappedString{
typedef char* string;
string storedString;
explicit operator string*(){
// some code
return &storedString;
}
explicit operator wrapperString*(){
// some code
return this;
}
operator string(){
// some code
return storedString;
}
}
$ c> if(wrappedStringObject == anotherWrappedStringObject){只会使用 string
重载,而不是 string * code> overload。
With that definition, if(wrappedStringObject == anotherWrappedStringObject){
will only use the string
overload, not the string*
overload.
这篇关于使用许多类型转换器操作员过载时的模糊过载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!