Date
May. 19th, 2024
 
2024年 4月 12日

Post: C++ Primer 012 : 支持自定义类型转换的构造函数

C++ Primer 012 : 支持自定义类型转换的构造函数

Published 12:05 May 25, 2013.

Created by @ezra. Categorized in #Programming, and tagged as #C/C++.

Source format: Markdown

Table of Content

本篇主要介绍C++ 中支持自定义类型转换的构造函数。

目标类::目标类(const 源类 &源类对象) {
    //自定义规则进行复制
    //可以使用初始化列表的方式
}
  • 实现从源类到目标类之间的隐式类型转换。

  • 使用explicit关键字修饰的构造函数,表示这个构造函数只能用于显式类型转换,防止潜在的错误。

/*
    支持自定义类型转换的构造函数userDefined.cpp
*/
#include <iostream>

using namespace std;

//声明Point2d
class Point2d;

class Point3d {
private:
    int m_x;
    int m_y;
    int m_z;
public:
    //explicit告诉编译器当前构造函数不支持自定义类型转换,也就是不能发生隐式类型转换,只能发生显式类型转换
    explicit Point3d(int x,int y,int z):m_x(x),m_y(y),m_z(z){}
    void show(void) {
        cout << "三维坐标(" << m_x << ',' << m_y << ',' << m_z << ')' << endl;
    }
    //提供一个支持自定义类型转换的构造函数
    Point3d(const Point2d &pt2);//:m_x(pt2.m_x),m_y(pt2.m_y),m_z(0){}
};

class Point2d {
private:
    int m_x;
    int m_y;
public:
    Point2d(int x,int y):m_x(x),m_y(y){}
    void show(void) {
        cout << "二维坐标(" << m_x << ',' << m_y << ')' << endl;
    }
    //声明Point3d类为当前类的友元
    friend class Point3d;
};

Point3d::Point3d(const Point2d &pt2):m_x(pt2.m_x),m_y(pt2.m_y),m_z(0){}

int main(void) {
    Point3d pt3(10,20,30);
    pt3.show();
    Point2d pt2(100,200);
    pt2.show();
    pt3 = pt2;
    pt3.show();
    pt3 = static_cast<Point3d>(100);
    pt3.show();
    return 0;
}
Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF