这段代码:
#include <iostream>
using ::std::cerr;
class Barney;
class Fred {
public:
Fred() { }
Fred(const Barney &b) { cerr << "Using conversion constructor.\n"; }
};
class Barney {
public:
Barney() { }
operator Fred() const { cerr << "Using conversion operator.\n"; return Fred(); }
};
int main(int argc, const char *argv[])
{
const Barney b;
Fred f;
f = b;
return 0;
}
在 gcc 4.6 中生成此错误:
g++ -O3 -Wall fred.cpp -o a.out
fred.cpp: In function ‘int main(int, const char**)’:
fred.cpp:23:8: error: conversion from ‘const Barney’ to ‘const Fred’ is ambiguous
fred.cpp:21:17: note: candidates are:
fred.cpp:16:4: note: Barney::operator Fred() const
fred.cpp:10:4: note: Fred::Fred(const Barney&)
fred.cpp:7:7: error: initializing argument 1 of ‘Fred& Fred::operator=(const Fred&)’
Compilation exited abnormally with code 1 at Sun Jun 19 04:13:53
现在,如果我删除const
after operator Fred()
,它就会编译并使用转换构造函数。如果我还从 in 的声明中删除了,const
那么它更喜欢转换运算符。b
main
这一切都符合重载决议规则。当 gcc 无法在转换运算符和转换构造函数之间进行选择时,它会生成适当的歧义错误。
我注意到在您提供的示例中,转换运算符缺少const
. 这意味着永远不会出现使用转换运算符或转换构造函数不明确的情况。