User-defined conversions
User-defined conversions allow you to specify object conversions with constructors or with conversion functions. User-defined conversions are implicitly used in addition to standard conversions for conversion of initializers, functions arguments, function return values, expression operands, expressions controlling iteration, selection statements, and explicit type conversions.
代码
代码
There are two types of user-defined conversions:
- Conversion by constructor
- Conversion functions
Conversion function syntax
>>-+-----------+--operator--+----------+--conversion_type------->
'-class--::-' +-const----+
'-volatile-'
>--+----------------------+--(--)--+---------------------+-----><
| .------------------. | '-{--function_body--}-'
| V | |
'---pointer_operator-+-'
代码 1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 public:
7 operator int();
8 };
9
10 A::operator int()
11 {
12 return 90;
13 }
14
15 int main(int argc, char *argv[])
16 {
17 A a;
18 cout << a << endl;
19 return 0;
20 }
21
22
2 using namespace std;
3
4 class A
5 {
6 public:
7 operator int();
8 };
9
10 A::operator int()
11 {
12 return 90;
13 }
14
15 int main(int argc, char *argv[])
16 {
17 A a;
18 cout << a << endl;
19 return 0;
20 }
21
22
结果:90
当有重载的operator << 的时候,会以operator<<更为优先
代码 1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 public:
7 operator int();
8 friend ostream& operator<<(ostream &os, A &a);
9 };
10
11 A::operator int()
12 {
13 return 90;
14 }
15
16 ostream &operator<<(ostream &os, A &a)
17 {
18 os << 30;
19 return os;
20 }
21 int main(int argc, char *argv[])
22 {
23 A a;
24 cout << a << endl;
25 return 0;
26 }
2 using namespace std;
3
4 class A
5 {
6 public:
7 operator int();
8 friend ostream& operator<<(ostream &os, A &a);
9 };
10
11 A::operator int()
12 {
13 return 90;
14 }
15
16 ostream &operator<<(ostream &os, A &a)
17 {
18 os << 30;
19 return os;
20 }
21 int main(int argc, char *argv[])
22 {
23 A a;
24 cout << a << endl;
25 return 0;
26 }
结果:30
当存在继承关系的时候,只有当派生类和基类转换成相同的类型的时候,派生类的conversion function才会隐藏掉基类的conversion function,否则不会隐藏。
构造函数类型转换参考以下链接
参考:
User-defined conversions
Conversion functionsConversion by constructor
MSDN Conversion by constructor


浙公网安备 33010602011771号