问题:
类类型是否可以类型转换到普通类型呢?ios
#include <iostream> using namespace std; class Test { }; int main() { Test t; int i = 0; i = t; return 0; }
输出: test.cpp: In function ‘int main()’: test.cpp:14: error: cannot convert ‘Test’ to ‘int’ in assignment
- C++ 类能够定义类型转换函数
- 类型转换函数用于将类对象转换为其它类型
语法规则:编程
operator Type () { Type ret; // ... return ret; }
#include <iostream> using namespace std; class Test { private: int mValue; public: Test(int i = 0) { mValue = i; } int value() { return mValue; } operator int () { return mValue; } }; int main() { Test t(100); int i = t; // <==> int i = t.operator int (); cout << "t.value() = " << t.value() << endl; cout << "i = " << i << endl; return 0; }
输出: t.value() = 100 i = 100
- 编译器会尽力尝试让源码经过编译
t 这个对象为 Test 类型,怎么可能用于初始化 int 类型的变量呢!如今就报错吗?不急,我看看有没有类型转换函数!OK,发现 Test 类中定义了 operator int () ,能够进行转换。函数
类型转换函数spa
- 与转换构造函数有同等的地位
- 使得编译器有能力将对象转化为其它类型
- 编译器可以隐式的使用类型转换函数
类类型之间的相互转换?!
类型转换函数 VS 转换构造函数code
#include <iostream> using namespace std; class Test; class Value { public: Value() { } explicit Value(Test& t) { } }; class Test { public: operator Value () { Value ret; cout << "operator Value ()" << endl; return ret; } }; int main() { Test t; Value v = t; // <==> Value v = t.operator Value (); return 0; }
输出: operator Value ()
注意:
当 Value 类中 Value(Test& t) {} 不使用 explicit 修饰,在编译时将与 Test 类中的 operator Value () 产生匹配冲突。对象
error: conversion from ‘Test’ to ‘Value’ is ambiguous note: candidates are: Test::operator Value() note: Value::Value(Test&)
- 没法抑制隐式的类型转换函数调用(当定义后)
- 类型转换函数可能与转换构造函数冲突
- 工程中以
Type toType()
的公有成员代替类型转换函数
#include <iostream> using namespace std; class Test; class Value { public: Value() { } explicit Value(Test& t) { } }; class Test { public: Value toValue () // 注意这里! { Value ret; cout << "operator Value ()" << endl; return ret; } }; int main() { Test t; Value v = t.toValue(); return 0; }
输出: operator Value ()
工程中不推荐使用类型转换函数。隐式的类型转换可能会产生意想不到的问题。ci
- C++ 类中能够定义类型转换函数
- 类型转换函数用于将类对象转换为其它类型
- 类型转换函数与转换构造函数具备同等的地位
- 工程中以
Type toType()
的公有成员函数代替类型转换函数
以上内容参考狄泰软件学院系列课程,请你们保护原创!编译器