5.3.1 系统预定义类型之间的转换
隐式转换
显式转换
int(3.5)
5.3.2 类类型与系统预定义类型之间的转换
1)系统预定义类型 - > 类类型
#include "iostream"
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) :real(r), imag(i) {} //构造函数
Complex(double r) {
//转换构造函数,将 系统预定义类型 转换为 类
//使用时,可以作为构造函数来使用,也可以yongyu无法运算时的类型转换
real = r;
imag = 0;
}
friend Complex operator+(const Complex& c1, const Complex& c2) { //友元符号转换
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
void print() {
cout << "real:" << real << " imag:" << imag << endl;
}
};
int main() {
Complex b(3.3); //转换构造函数yongyu构造
Complex c = b + 1; //转换构造函数用于pipei自定义符号运算
c.print();
}
2)系统预定义类型 < - 类类型
#include "iostream"
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) :real(r), imag(i) {} //构造函数
operator double() {
//将class转换为double
//
//类可以转化成多种系统预定义类型 只能使用成员函数,不能使用友元函数
//没有参数,但有返回值 ( 不需要指定返回值的类型 )
return real;
}
friend Complex operator+(const Complex& c1, const Complex& c2) { //友元符号转换
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
void print() {
cout << "real:" << real << " imag:" << imag << endl;
}
};
int main() {
Complex a( 1.1 , 2.2 );
cout<< a + 1; //转换函数用于pipei相应的运算
}
类可以转化成多种系统预定义类型 只能使用成员函数,不能使用友元函数
没有参数,但有返回值 ( 不需要指定返回值的类型 )