C++语言基础(22)-转换构造函数和类型转换函数
一.转换构造函数
将其它类型转换为当前类类型需要借助转换构造函数(Conversion constructor)。转换构造函数也是一种构造函数,它遵循构造函数的一般规则。转换构造函数只有一个参数。
#include <iostream> using namespace std; //复数类 class Complex{ public: Complex(): m_real(0.0), m_imag(0.0){ } Complex(double real, double imag): m_real(real), m_imag(imag){ } Complex(double real): m_real(real), m_imag(0.0){ } //转换构造函数 public: friend ostream & operator<<(ostream &out, Complex &c); //友元函数 private: double m_real; //实部 double m_imag; //虚部 }; //重载>>运算符 ostream & operator<<(ostream &out, Complex &c){ out << c.m_real <<" + "<< c.m_imag <<"i";; return out; } int main(){ Complex a(10.0, 20.0); cout<<a<<endl; a = 25.5; //调用转换构造函数 cout<<a<<endl; return 0; }
运行结果:
10 + 20i
25.5 + 0i
二.类型转换函数
#include <iostream> using namespace std; //复数类 class Complex{ public: Complex(): m_real(0.0), m_imag(0.0){ } Complex(double real, double imag): m_real(real), m_imag(imag){ } public: friend ostream & operator<<(ostream &out, Complex &c); friend Complex operator+(const Complex &c1, const Complex &c2); operator double() const { return m_real; } //类型转换函数 private: double m_real; //实部 double m_imag; //虚部 }; //重载>>运算符 ostream & operator<<(ostream &out, Complex &c){ out << c.m_real <<" + "<< c.m_imag <<"i";; return out; } //重载+运算符 Complex operator+(const Complex &c1, const Complex &c2){ Complex c; c.m_real = c1.m_real + c2.m_real; c.m_imag = c1.m_imag + c2.m_imag; return c; } int main(){ Complex c1(24.6, 100); double f = c1; //相当于 double f = Complex::operator double(&c1); cout<<"f = "<<f<<endl; f = 12.5 + c1 + 6; //相当于 f = 12.5 + Complex::operator double(&c1) + 6; cout<<"f = "<<f<<endl; int n = Complex(43.2, 9.3); //先转换为 double,再转换为 int cout<<"n = "<<n<<endl; return 0; }
运行结果:
f = 24.6
f = 43.1
n = 43
注意:最好不要同时使用转换构造函数和类型转换函数,因为这样会导致语义的二义性。
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库