C++转换构造函数和类型转换函数_梵希栀子的博客-CSDN博客_c++转换构造函数
转换构造函数:
1、作用:其他类型转换(普通数据类型或者其他)——> 自定义对象
2、书写格式:Complex (double r) { } //要求形参只能有一个参数
3、注意点:转换构造函数配合使用运算符重载函数实现操作数交换律,要求是运算符重载函数是友元函数。
类型转换函数:
1、作用:自定义对象 ——> 普通类型
2、书写格式:operator double() { return real; } //要求函数名称为要转换的类型且函数无形参
3、注意点:与运算符重载具有二义性,使用过程中需要注意。
比如说,转换构造函数可以把double类型隐式转换为Complex对象,实现Complex +double=Complex 的运算 ;
而类型转换函数是相反的,把Complex对象隐式转换成double对象,实现Complex +double=double。
1.转换构造函数
#include<iostream>
using namespace std;
class Complex {
public:
Complex (double r) { // 转换构造函数
real = r;
imag = 0;
}
Complex() {
real = 0;
imag = 0;
}
Complex(double r, double m) {
real = r;
imag = m;
}
double getReal(){
return real;
}
double getImag(){
return imag;
}
void display(){
std::cout << real << " + " << imag << "i\n";
}
friend Complex operator+(Complex c1, Complex c2); // 友元函数实现运算符重载
friend std::ostream& operator<<(std::ostream& output, Complex& c);
private:
double real;
double imag;
};
Complex operator+(Complex c1, Complex c2){
return Complex(c1.real+c2.real, c1.imag+c2.imag);
}
std::ostream& operator<<(std::ostream& output, Complex& c){
return output << c.real << " + " << c.imag << "i";
}
int main(){
Complex c1(3.6, 2);
c1.display();
std::cout << "real: " << c1.getReal() << ", imag: " << c1.getImag() << "\n";
double d2 = 2.1234;
Complex c2 = c1 + d2; // 重载+
c2.display();
std::cout << c2 << "\n"; // 重载<<
c2 = d2 + c1;
c2.display();
}
2.类型转换函数
#include<iostream>
using namespace std;
class Complex {
public:
Complex() {
real = 0;
imag = 0;
}
Complex(double r, double m) {
real = r;
imag = m;
}
// 类型转换函数 类似于运算符重载的写法,1、要求函数名称为要转换的类型 2、函数无形参
operator double(){
return real;
}
double getReal(){
return real;
}
double getImag(){
return imag;
}
void display(){
std::cout << real << " + " << imag << "i\n";
}
private:
double real;
double imag;
};
int main(){
Complex c1(3.6, 2);
double d1 = 2.1234;
double d2 = c1 + d1;
std::cout << "d2: " << d2 << "\n";
double d3 = d1 + c1;
std::cout << "d3: " << d3 << "\n";
}