我们有这个代码:
- Test1 t1;
- Test2 t2;
- t1 = t2;
我相信有三种(或更多?)方法如何实现t1 = t2
>在Test1中重载赋值运算符
>在Test2中重载类型转换操作符
>创建Test1(const Test2&)转换构造函数
根据我的GCC测试,这是使用的优先级:
>分配操作符
>转换构造函数和类型转换操作符(不明确)
> const转换构造函数和const类型转换运算符(不明确)
请帮我理解为什么这个优先.
我使用此代码进行测试(取消注释某些行以试用)
- 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;
- }