#include <string>
struct String
{
template<typename T> operator T*() { return 0; }
operator std::string() { return ""; }
};
int main()
{
String myStr;
std::string str1(myStr); // ambiguous, error C2668
std::string str2 = myStr; // error C2440:
// 'initializing' : cannot convert from 'String' to
// `std::basic_string<char,std::char_traits<char>,std::allocator<char>>',
// No constructor could take the source type,
// or constructor overload resolution was ambiguous
const std::string& rStr = myStr; // Ok, but why?
}
我正在使用VS 2013。
问题:
为什么
str1
和str2
的定义会导致不同的编译错误?据我所知,当创建
rStr
时,首先会创建一个临时字符串对象,然后rStr
将引用该临时对象。但是,为什么创建临时对象不会导致编译错误?tmp
和strN
之间是否有任何区别?
str2
的定义和初始化。 - dyp