数据类型转换通过内置的数据类型在 "幕后" 发生。例如,假设程序使用以下变量:
int i;
double d;
d = i;
同样,以下语句会将d中的值转换为整数(截断小数部分)并将其存储在i中:i = d;
类对象也可以使用相同的功能。例如,假设 distance 是一个 Length 对象,d 是一个 double,如果 Length 被正确编写,则下面的语句可以方便地将 distance 作为浮点数存储到 d 中:d = distance;
为了能够像这样使用语句,必须编写运算符函数来执行转换。以下就是一个将 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. hnLength::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;}程序输出结果:
The Length object is 4 feet,6 inches.
The Length object measures 4.5 feet.
The Length object measures 54 inches.
以上是内存溢出为你收集整理的C++类型转换运算符(无师自通)全部内容,希望文章能够帮你解决C++类型转换运算符(无师自通)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)