我遇到了以下代码的编译错误:
我遇到了以下代码的编译错误:
class SymbolGroup
{
std::string d_;
public:
SymbolGroup(std::string a):d_(a){}
// explicit operator const std::string&() const { return d_;} // compiles
explicit operator std::string() const { return d_;} // Does not compile
};
inline
bool operator==(const SymbolGroup& lhs, const SymbolGroup& rhs)
{
return static_cast<const std::string&>(lhs) ==
static_cast<const std::string&>(rhs);
}
int main(){
SymbolGroup a("hello");
SymbolGroup b("hello");
if (a==b)
std::cout << "they are the same\n";
return 0;
}
如果在用户定义的类型转换行中没有使用 'const' 和 '&',则在使用 --std=c++11 标志的 g++ (4.8) 中无法编译:
错误:无效的引用初始化类型 'std::string& {aka std::basic_string&}',表达式类型为 'const string {aka const std::basic_string}' explicit operator std::string&() const { return d_;}
这段代码可以在 Clang 上两种方式都编译。哪个编译器是正确的?这段代码应该编译吗 operator std::string()
?