类型转换

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

主要用于其它类型到本类类型的转化。

  • 转换构造函数格式
class 目标类型 
{
        目标类型(const 源类型 & 源类型变量/对象引用)
        {
                根据需求完成从源类型到目标类型的转换
    } 
}
  • 特点

    转换构造函数,本质是一个构造函数。是只有一个参数的构造函数。如有多个参数,
    只能称为构造函数,而不是转换函数。

  • 代码举例

#include <iostream>
using namespace std;
class Point3D;
class Point2D
{
public:
    Point2D(int x, int y) : _x(x), _y(y) {}
    void dis()
    {
        cout << "(" << _x << "," << _y << ")" << endl;
    }
    friend Point3D; //friend Point3D::Point3D( Point2D &p2);

private:
    int _x;
    int _y;
};
class Point3D
{
public:
    Point3D(int x, int y, int z) : _x(x), _y(y), _z(z) {}
    Point3D(Point2D &p)
    {
        this->_x = p._x;
        this->_y = p._y;
        this->_z = 0;
    }
    void dis()
    {
        cout << "(" << _x << "," << _y << "," << _z << ")" << endl;
    }

private:
    int _x;
    int _y;
    int _z;
};
int main()
{
    Point2D p2(1, 2);
    p2.dis();
    Point3D p3(3, 4, 5);
    p3.dis();
    Point3D p3a = p2;
    p3a.dis();
    return 0;
}

explicit关键字

在构造函数声明中使用explicit可防止隐式转换,而只允许强制类型转换。

如在上面代码中加入explicit关键字后:
explicit Point3D(Point2D &p)
{
     this->_x = p._x;
     this->_y = p._y;
     this->_z = 0;
}
...
Point3D p3a = p2;                       //error,无法实现隐式转换
Point3D p3a = (Point3D)p2; //right 强制类型转换

转换函数

  • 转换函数格式

    class 源类型
    {
          operator 转化目标类型(void) 
          {
              根据需求完成从源类型到目标类型的转换
          } 
    }
    
  • 特点

    转换函数必须是类方法,转换函数无参数,无返回

  • 代码举例

    #include <iostream>
    using namespace std;
    class Point3D;
    class Point2D
    {
    public:
        Point2D(int x, int y) : _x(x), _y(y) {}
        operator Point3D();
        void dis()
        {
            cout << "(" << _x << "," << _y << ")" << endl;
        }
    
    private:
        int _x;
        int _y;
    };
    class Point3D
    {
    public:
        Point3D(int x, int y, int z)
            : _x(x), _y(y), _z(z) {}
        void dis()
        {
            cout << "(" << _x << "," << _y << "," << _z << ")" << endl;
        }
    
    private:
        int _x;
        int _y;
        int _z;
    };
    Point2D::operator Point3D()
    {
        return Point3D(_x, _y, 0);
    }
    int main()
    {
        Point2D p2(1, 2);
        p2.dis();
        Point3D p3(3, 4, 5);
        p3.dis();
        Point3D p3a = p2;
        p3a.dis();
        return 0;
    }
    
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容