大佬教程收集整理的这篇文章主要介绍了C++类型转换运算符(无师自通),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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. 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; }程序输出结果:
The Length object is 4 feet,6 inches.
The Length object measures 4.5 feet.
The Length object measures 54 inches.
以上是大佬教程为你收集整理的C++类型转换运算符(无师自通)全部内容,希望文章能够帮你解决C++类型转换运算符(无师自通)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。