acu*_*tea 1 c++ implicit-conversion
例子:
struct c{
void operator=(bool){}
operator bool(){
return false;
}
c&operator=(const c&)=delete;
};
void f(bool){}
int main(){
c a,b;
f(b); //works fine
a=b; //g++ -std=c++17 says: error: use of deleted function ‘c& c::operator=(const c&)’
}
Run Code Online (Sandbox Code Playgroud)
为什么f(b)调用转换b为boolmatchf的类型但a=b坚持不转换?
重载解析的工作原理是找到最佳匹配,然后检查函数的可访问性。如果您无法访问该功能,因为它受保护/私有或已删除,那么您会收到错误消息。和
f(b);
Run Code Online (Sandbox Code Playgroud)
唯一有效的选项是operator bool()使代码有效。和
a=b
Run Code Online (Sandbox Code Playgroud)
编译器发现
c&operator=(const c&)
// and the chain
operator bool() -> void operator=(bool)
Run Code Online (Sandbox Code Playgroud)
第一个是更好的匹配,所以它是使用的重载,并且由于它被标记为delete,你会得到一个编译器错误。
| 归档时间: |
|
| 查看次数: |
42 次 |
| 最近记录: |