类的强制类型转换

在代码编辑过程中,我们或许会希望建立一个基本类型变量,使其直接等于类中的对应变量,当变量位于类中的私有部分时,我们可以通过类方法来实现(成员函数)。

  • 我们希望建立一个更加轻量化的强制转换函数,实现上述功能:

    During the code editing process, we might want to create a variable of a basic type and make it directly equal to the corresponding variable in the class. When the variable is in the private part of the class, we can achieve this through class methods (member functions).

    We want to create a type conversion function to achieve the above functionality:

代码如下:

#include<iostream>
using namespace std;
class ss
{
    private:
    int a;
    int force; // 要转换的对象
    double x;
    double y; // 要转换的对象
    public:
    ss();
    ss(int,int,double,double);
    operator int();
    operator double();
};
ss::ss()
{
    a = force = 0;
    x = y = 0.0;
}
ss::ss(int q,int w,double e,double r)
{
    a = q;
    force = w;
    x = e;
    y = r;
}
ss::operator int() // 转换函数
{
    return force;
}
ss::operator double() // 转换函数
{
    return y;
}
int main()
{
    ss a(12,56,23.68,56.788);
    int s = a;
    double q = a;
    cout << s << endl; //56
    cout << q << endl; //56.788
    cout << int(a) << endl; // 另一种格式
    cout << double(a) << endl; // 另一种格式
    system("pause");
    return 0;
}

#include<iostream>
using namespace std;
class ss
{
    private:
    int a;
    int force; // The object to be converted
    double x;
    double y; // The object to be converted
    public:
    ss();
    ss(int,int,double,double);
    operator int();
    operator double();
};
ss::ss()
{
    a = force = 0;
    x = y = 0.0;
}
ss::ss(int q,int w,double e,double r)
{
    a = q;
    force = w;
    x = e;
    y = r;
}
ss::operator int() // Conversion function
{
    return force;
}
ss::operator double() // Conversion function
{
    return y;
}
int main()
{
    ss a(12,56,23.68,56.788);
    int s = a;
    double q = a;
    cout << s << endl; //56
    cout << q << endl; //56.788
    cout << int(a) << endl; // Another format
    cout << double(a) << endl; // Another format
    system("pause");
    return 0;
}

  • 但应该注意,我们应当谨慎使用隐式调用,最好使用显示调用:
class ss
{
    private:
    int a;
    int force; // The object to be converted
    double x;
    double y; // The object to be converted
    public:
    ss();
    ss(int,int,double,double);
    explicit operator int();
    explicit operator double();
};
  • 使用explicict 将避免使用隐式转换,只可以显式转换

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值