欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

C++:转换构造函数与类型转换实用技巧

最编程 2024-07-26 22:31:55
...
(1)转换构造函数

转换构造函数只有一个参数,代码非常简单:

class Student
{
public:
    Student() {}

    Student(int age) // 转换构造函数
    {
        mAge = age;
    }
    int getAge()
    {
        return mAge;
    }
private:
    int mAge;
};

int main() {


    Student student;
    student = 101;
    cout << student.getAge() << endl;

    return 0;
}

输出结果为:

101

Student 类中有一个构造函数只有一个参数,在初始化时,可以这样:

Student student(10);

然而,只有一个参数的构造函数又符合 转换构造函数,它的初始化也可以这样写:

Student student;
student = 101;

Student 的唯一的成员变量是整数类型的,它也可以是类类型,代码如下:

class Book 
{
public:
    Book() {}
    Book(int a):mA(a) {}
    int getA() 
    {
        return mA;
    }
private:
    int mA;
};

class Student
{
public:
    Student() {}

    Student(const Book& book) // 转换构造函数
    {
        mBook = book;
    }
    Book getBook()
    {
        return mBook;
    }
private:
    Book mBook;
};

int main() {

    Book book(10);
    Student student;
    student = book;
    cout << student.getBook().getA() << endl;

    return 0;
}

我们提取两者类型转换的代码:

student = 101;

student = book;

前者是基本数据类型转成类类型,后者是两个不同的类类型转换。

(2)类类型转换函数

类类型转换函数使用重载运算符的方式实现的,重载运算符可以让一个类型转成另一个类型。

【使用赋值运算符】

将一个类对象转成另一个类对象。

class Book 
{
public:
    Book() {}
    Book(int a):mA(a) {}
    int getA() 
    {
        return mA;
    }
private:
    int mA;
};

class Student
{
public:
    Student() {}

    void operator=(const Book& book) // 赋值运算符的重载
    {
        mBook = book;
    }

    Book getBook()
    {
        return mBook;
    }
private:
    Book mBook;
};

int main() {

    Book book(10);
    Student student;
    student = book;
    cout << student.getBook().getA() << endl;

    return 0;
}

【使用强制类型转换运算符】

将类对象转成基本数据类型。

class Student
{
public:
    Student():mA(10) {}

    operator double() // 强制类型转换运算符的重载
    {
        return mA;
    }

    double getA()
    {
        return mA;
    }
private:
    double mA;
};

int main() {

    Student student;
    double n = student;
    cout << n << endl;

    return 0;
}

[本章完...]