我们知道,运算符函数允许类更像内置数据类型一样工作。运算符函数可以赋予类的另一个功能是自动类型转换。
数据类型转换通过内置的数据类型在 "幕后" 发生。例如,假设程序使用以下变量:
那么以下语句会自动将i中的值转换为 double 并将其存储在 d 中:
同样,以下语句会将d中的值转换为整数(截断小数部分)并将其存储在i中:
类对象也可以使用相同的功能。例如,假设 distance 是一个 Length 对象,d 是一个 double,如果 Length 被正确编写,则下面的语句可以方便地将 distance 作为浮点数存储到 d 中:
为了能够像这样使用语句,必须编写运算符函数来执行转换。以下就是一个将 Length 对象转换为 double 的运算符函数:
- Length::operator double() const
- {
- return len_inches /12 + (len_inches %12) / 12.0;
- }
该函数计算以英尺为单位的长度测量的实际十进制等效值。例如,4 英尺 6 英寸的尺寸将被转换为实数 4.5。
下面的程序演示了带有 double 和 int 转换运算符的 Length 类。int 运算符将只是返回 Length 对象的英寸数。
- //Length2.h的内容
- #ifndef _LENGTH1_H
- #define _LENGTH1_H
- #include <iostream>
- using namespace std;
-
- class Length
- {
- private:
- int len_inches;
- public:
- Length(int feet, int inches)
- {
- setLength(feet, inches);
- }
- Length(int inches){ len_inches = inches; }
- int getFeet() const { return len_inches / 12; }
- int getInches() const { return len_inches % 12; } void setLength(int feet, int inches)
- {
- len_inches = 12 *feet + inches;
- }
- // Type conversion operators
- operator double() const;
- operator int () const { return len_inches; }
- // Overloaded stream output operator
- friend ostream &operator << (ostream &out, Length a);
- };
- #endif
-
- //Length2.cpp 的内容
- #include T,Length2. hn
- Length::operator double() const
- {
- return len_inches /12 + (len_inches %12) / 12.0;
- }
- ostream &operator<<(ostream& out, Length a)
- {
- out << a.getFeet() << " feet, " << a.getInches() << " inches";
- return out;
- }
-
- // This program demonstrates the type conversion operators for the Length class.
- #include "Length2.h"
- #include <iostream>
- #include <string>
- using namespace std;
-
- int main()
- {
- Length distance(0);
- double feet;
- int inches;
- distance.setLength(4, 6);
- cout << "The Length object is " << distance << "." << endl;
- // Convert and print
- feet = distance;
- inches = distance;
- cout << "The Length object measures" << feet << "feet." << endl;
- cout << "The Length object measures " << inches << " inches." << endl;
- return 0;
- }
程序输出结果: