C++类型转换运算符(无师自通)

  • 内容
  • 评论
  • 相关

我们知道,运算符函数允许类更像内置数据类型一样工作。运算符函数可以赋予类的另一个功能是自动类型转换

数据类型转换通过内置的数据类型在 "幕后" 发生。例如,假设程序使用以下变量:

int i;
double d;

那么以下语句会自动将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++类型转换运算符(无师自通)

本文地址:https://www.hosteonscn.com/3870.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注