有人可以解释转换规则,以及何时转换不明确吗?我对以下案例感到有些困惑,它在 MSVC++ (Visual Studio 2010) 和 gcc-4.3.4 上给出了不同的答案。
#include <string>
class myStr
{
std::string value;
public:
myStr(const char* val) : value(val) {}
operator const char*() const {return value.c_str();}
operator const std::string() const {return value;}
};
myStr byVal();
myStr& byRef();
const myStr& byConstRef();
int main(int, char**)
{
myStr foo("hello");
std::string test;
// All below conversions fail "ambiguous overload for 'operator='" in gcc
// Only the indicated coversions fail for MSVC++
test = foo; // MSVC++ error "'operator =' is ambiguous"
test = static_cast<std::string>(foo);
test = byVal(); // MSVC++ error "'operator =' is ambiguous"
test = static_cast<std::string>(byVal()); // MSVC++ error
// "'static_cast' : cannot convert from 'myStr' to 'std::string'"
test = byRef(); // MSVC++ error "'operator =' is ambiguous"
test = static_cast<std::string>(byRef());
test = byConstRef(); // MSVC++ error "'operator =' is ambiguous"
test = static_cast<std::string>(byConstRef());
return 0;
}
哪些规则规定哪些转换是合法的?是否有任何合规的方法可以明确地使用一个myStr
定义强制转换为const char*
和的类const std::string
?