问题描述
让我们有这个代码:
Test1(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(){}
//操作符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;
}
c> t1 = t2; 等效于:
t1.operator =
现在通常的重载解决规则适用。如果有直接匹配,那就是所选的匹配。如果不是,那么隐式转换被认为用于(自动生成的,隐式定义)拷贝赋值运算符。
有两种可能的隐式,用户定义转换。所有用户定义的转化计数相等,如果两者都定义,则重载是不明确的:
-
转换 Test1 :: Test1(Test2 const&)到
-
将 t2 转换为 Test1 通过 Test2 :: operator Test1()const cast运算符。
Let's have this code:
Test1 t1; Test2 t2; t1 = t2;
I believe there are three (or more?) ways how to implement t1 = t2
- to overload assign operator in Test1
- to overload type cast operator in Test2
- to create Test1(const Test2&) conversion constructor
According to my GCC testing, this is the priority of what is used:
- assign operator
- conversion constructor and type cast operator (ambiguous)
- const conversion constructor and const type cast operator (ambiguous)
Please help me understand why this priority.
I use this code for testing (uncomment some lines to try out)
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; }
The statement t1 = t2; is equivalent to:
t1.operator=(t2);
Now the usual rules of overload resolution apply. If there's a direct match, that's the chosen one. If not, then implicit conversions are considered for use with the (automatically generated, "implicitly defined") copy-assignment operator.
There are two possible implicit, user-defined conversions. All user-defined conversions count equal, and if both are defined, the overload is ambiguous:
Convert t2 to a Test1 via the Test1::Test1(Test2 const &) conversion constructor.
Convert t2 to a Test1 via the Test2::operator Test1() const cast operator.
这篇关于c ++:cast操作符与赋值运算符与转换构造函数优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!