Jan*_*roň 8 c++ casting copy-constructor assignment-operator
我们有这个代码:
Test1 t1;
Test2 t2;
t1 = t2;
Run Code Online (Sandbox Code Playgroud)
我相信有三种(或更多?)方法如何实施 t1 = t2
Test1Test2Test1(const Test2&)转换构造函数根据我的GCC测试,这是使用的优先级:
请帮我理解为什么这个优先.
我使用此代码进行测试(取消注释某些行以试用)
struct Test2;
struct Test1 {
Test1() { }
Test1(const Test2& t) { puts("const constructor wins"); }
// Test1(Test2& t) { puts("constructor wins"); }
// Test1& operator=(Test2& t) { puts("assign wins"); }
};
struct Test2 {
Test2() { }
// operator Test1() const { puts("const cast wins"); return Test1(); }
// operator Test1() { puts("cast wins"); return Test1(); }
};
int main() {
Test1 t1;
Test2 t2;
t1 = t2;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Ker*_* SB 13
该声明t1 = t2;相当于:
t1.operator=(t2);
Run Code Online (Sandbox Code Playgroud)
现在通常的重载决策规则适用.如果有直接匹配,那就是所选择的.如果不是,则认为隐式转换与(自动生成的,"隐式定义的")复制赋值运算符一起使用.
有两种可能的隐式用户定义转换.所有用户定义的转换计数相等,如果两者都定义,则重载不明确:
通过转换构造函数转换t2为a .Test1Test1::Test1(Test2 const &)
通过强制转换运算符转换t2为a .Test1Test2::operator Test1() const