【发布时间】:2012-07-20 20:35:25
【问题描述】:
我有一个这样的结构:
struct VrtxPros{
long idx;
std::vector<std::string> pros;
VrtxPros(const long& _idx=-1, const std::string& val="") : idx(_idx)
{
if ( !val.empty() && val!="" )
pros.push_back(val);
}
};
后来在代码中我这样使用它:
long idx = 1234;
VrtxPros vp( 2134, std::string("-1") );
if ( margin ) vp.pros[0] = idx;
编译器对此没有任何问题。我想知道,因为运营商应该提供参考。
我could not find 和operator= 中的std::string 将接受long 作为源。
为什么代码会编译?
【问题讨论】:
-
basic_string& operator=( CharT ch ); 4) Replaces the contents with character ch。您的long可能正在转换为字符。其他需要注意的是,如果我没有遗漏某些内容,您的!= ""检查是多余的,并且传递"-1"很好,因为std::string具有const char *的隐式转换构造函数。 -
@mistapink,long 可以隐式转换为
char。 ideone.com/wNd4u -
@mistapink,对于
CharT,它是std::basic_string<>的第一个模板参数,即charforstd::string。为了比较,CharT将是wchar_t对应于std::wstring。 -
g++ 将 int 隐式转换为 char..
-
@Hrishi,g++ 不应该是唯一的:
int x = 999; ...; char c1 = x; // OK, though it might narrow (in this case, it does narrow)取自 C++11 标准,第 8.5.4 节
标签: c++ vector type-conversion