C++学习 十四、类的进阶(3)自动类型转换,强制类型转换
前言
- 前言
- 内置类型的转换
- 类的转换
- 其它类型转换为类
- explicit关键字
- 转换为类的二义性
- 常见的类转换
- 类转换为内置类型
- explicit关键字
- 转换为内置类型二义性
- 后记
本篇继续类的进阶学习,自动类型转换和强制类型转换。
内置类型的转换C++的内置类型具有自动转换(隐式)和强制转换(显式)。
只要类型兼容,就能自动转换:
int x = 1.66; // double to int
float y = 2; // int to float
long z = y; // float to long
否则,只能使用强制转换:
int* px = (int*) 100;
int p = long (&p);
// int p = int (&p); // error!
注意:int p = int(&p);
将报error: cast from 'int*' to 'int' loses precision [-fpermissive]
,我查了一下stack overflow,下面这个答案说的挺清楚,原因是将指针转换为int类型后丢失了精度,并且没法再重构这个指针,也就是出现了信息丢失,因此编译器不让过。
C++设计者希望,自定义的类型也能够和内置类型一样能够与其它类型进行转换。
于是,类也能够进行自动转换(隐式)和强制转换(显式)。
其它类型转换为类只接受一个参数的构造函数将成为其它类型转换为类,示例如下:
#include
#include
using std::ostream;
class B{
private:
int a_;
double b_;
public:
friend class A;
B();
B(int, int);
};
B::B(){
a_ = 100;
b_ = 100;
}
B::B(int a, int b){
a_ = a;
b_ = b;
}
class A{
private:
int a_;
double b_;
public:
A();
A(int);
A(double);
A(const B&, bool flag=true);
friend ostream& operator
关注
打赏