class ConvertTo {};
class COnvertable
{
public:
explicit operator ConvertTo () const
{
return ConvertTo();
};
};
void Func(ConvertTo ct)
{
}
void test ()
{
COnvertable c;
ConvertTo ct(c); // 调用1
// ConvertTo ct2 = c;
ConvertTo ct3 = static_cast<ConvertTo>(c);
// Func(c);
}
问题:调用1不是调用ConverTo的拷贝构造函数吗?假如是的话为什么c不用进行显示转换成ConverTo也能成功呢?
class COnvertable
{
public:
explicit operator ConvertTo () const
{
return ConvertTo();
};
};
void Func(ConvertTo ct)
{
}
void test ()
{
COnvertable c;
ConvertTo ct(c); // 调用1
// ConvertTo ct2 = c;
ConvertTo ct3 = static_cast<ConvertTo>(c);
// Func(c);
}
问题:调用1不是调用ConverTo的拷贝构造函数吗?假如是的话为什么c不用进行显示转换成ConverTo也能成功呢?
解决方案
20
这种没问题,假如写成ConvertTo ct2 = c;才是错误的
参看:http://en.cppreference.com/w/cpp/language/explicit 中例子
参看:http://en.cppreference.com/w/cpp/language/explicit 中例子
10
12.3.2 Conversion functions
2 A conversion function may be explicit (7.1.2), in which case it is only considered as a user-defined conversion for direct-initialization (8.5). Otherwise, user-defined conversions are not restricted to use in assignments
and initializations.
2 A conversion function may be explicit (7.1.2), in which case it is only considered as a user-defined conversion for direct-initialization (8.5). Otherwise, user-defined conversions are not restricted to use in assignments
and initializations.
是。
// 标准允许实现上省略拷贝构造的调用,但语义上这里是有一个拷贝构造的。
// 你可以把拷贝构造 private 掉或 delete 掉看看效果
见上,explicit 类型转换运算符仅在 direct initialization 中有效。调用1 是 direct initialization,所以类型转换运算符有效。
使用的构造仍然是拷贝构造。