我正在尝试理解static_cast。我有两个类 From 和 To 。我正在尝试将从转换为到。我有一个 To 的构造函数,它带有 From 。我还有一个用户定义的转换运算符,用于将 From 对象转换为 To 。为什么构造函数优先于赋值运算符?
class From;
class To
{
public:
int y;
To() { cout << "In To default constructor" << endl; }
To(const To& sl2) { cout << "In To copy constructor" << endl; }
void operator=(const To& sl2) { cout << "In To assignment operator" << endl; }
~To() { cout << "In To destructor" << endl; }
To(const From& sl1) { cout << "In From-To constructor" << endl;}
};
class From
{
public:
int x;
From() { cout << "In From default constructor" << endl; }
From(const From& sl2) { cout << "In From copy constructor" << endl; }
void operator=(const From& sl2) { cout << "In From assignment operator" << endl; }
~From() { cout << "In From destructor" << endl; }
operator To() const { cout << "Converting From to To" << endl; return To(); }
};
int _tmain(int argc, _TCHAR* argv[])
{
From from;
To to;
to = static_cast<To>(from);
}
答案 0 :(得分:5)
是&#34;因为标准是这么说的&#34;一个有效的答案?
<div class="btn-group pull-right" style="z-index:1000">
...
</div>
与static_cast<T>(e)
具有相同的效果,其中T t(e);
是演员的结果。这遵循 direct-initialization 的规则,它在考虑用户定义的转换序列之前通过重载解析来考虑适用的构造函数。
如果可以让您放心,我可以提供相关的标准报价。