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;
}
[本章完...]
上一篇: 地址转换函数
推荐阅读
-
全面学习C++编程2(侯捷视频全集):掌握转换函数、显式类型转换、智能指针、成员模板等重要概念与技术
-
玩转Oracle:concat、convert和listagg函数的妙用(字符串拼接与类型转换)
-
C++中的转换构造函数详解
-
玩转C++:理解与应用转换函数(Conversion Function)
-
在C++中:转换构造函数与隐式类型转换的运用
-
在C++中:转换构造函数与隐式类型转换的运用
-
在 C++ 中:构造函数转换与强制类型转换的运用
-
C++中的转换函数详解:第二部分 - 应用与用法
-
深入解析 SQL Server:从数据类型转换到文本与图片处理 - 第二部分:详细解读文本和图像函数
-
全面攻略:C/C++语言中的各类数据类型转换函数集锦