【C++】学习笔记草稿版12(类对象的类型转换)

错误的写法

float(5)/8

正确的写法

(float)5/8; static_cast<float>(5)/8;

用类型转换构造函数进行类型转换

实现其它类型本类类型的转化。
转换构造函数格式

class 目标类
{
    目标类(const 源类 & 源类对象引用)
    {
        根据需求完成从源类型到目标类型的转换
    }
}
class Point2D
{
public:
    Point2D(int x, int y)
        :_x(x), _y(y){}
    friend class Point3D;
private:
    int _x;
    int _y;
};

class Point3D
{
public:
    Point3D(int x, int y, int z)
        :_x(x), _y(y), _z(z){}

    Point3D operator=(const Point3D & another)
    {
        this->_x = another._x;
        this->_y = another._y;
        this->_z = another._z;
        return *this;
    }
    Point3D(const Point2D & p2)
    {
        this->_x = p2._x;
        this->_y = p2._y;
        this->_z = 0;
    }

    void dis()
    {
        cout<<"("<<_x<<", "<<_y<<", "<<_z<<")"<<endl;
    }
privateint _x;
    int _y;
    int _z;
};

int main()
{
    Point2D p2(1, 2);
    Point3D p3(3, 4, 5);

    p3 = p2; //先把p2升级为3D类型,然后发生的是一种赋值
    p3.dis();
    return 0;
}

我们把这一类单参的构造器称为类型转化构造器。
用于:赋值、传参

转换构造函数,本质是一个构造函数。是只有一个参数的构造函数。如有多个参数,只能称为构造函数,而不是转换函数。转换函数指的是一对一的关系
explicit
如果转换构造函数添加了explicit修饰,则在进行转换构造的时候应该使用语句

p3 = (Point3D)p2;
p3 = static_cast<Point3D>(p2);

implicit

用类型转换操作符函数进行转换

类型转化函数格式
class 源类
{
    operator 转化目类型(void)
    {
        根据需求完成从源类型到目标类型的转换
    }
}
class Point2D
{
public:
    Point2D(int x, int y)
        :_x(x), _y(y){}

private:
    int _x;
    int _y;
};

class Point3D
{
public:
    Point3D(int x, int y, int z)
        :_x(x), _y(y), _z(z){}
    // 无参无返回
    operator Point2D(void)
    {
        return Point2D(this->_x, this->_y);
        //语法规定,不要问为什么
    }

    void dis()
    {
        cout<<"("<<_x<<", "<<_y<<", "<<_z<<")"<<endl;
    }

privateint _x;
    int _y;
    int _z;
};

int main()
{
    Point3D p3(1, 2, 3);

    Point2D p2(0, 0);

    p2 = p3;
    p2.dis();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值