听侯捷老师的讲课笔记:
所谓转换函数指的是类型之间的转换,比如把自定义的类类型转换成内建类型(比如double),后者向相反的方向转。
直接上代码:
头文件conversion_function.h:
#pragma once #include<iostream> using namespace std; class Fraction { public: Fraction(int num,int den=1):m_numerator(num),m_denominator(den) { cout << "构造函数 被调用了哦!!!" << endl; } ~Fraction(){ cout << "析构 函数被调用了哦!!!" << endl; } operator double()const { return (double)(m_numerator / m_denominator); } private: double m_numerator; double m_denominator; };
源文件conversion_function.cpp:
#include"conversion_function.h" int main() { Fraction f(1, 5); cout << f.operator double() << endl; double d = 4 + f; cout <<"d: "<< d << endl; system("pause"); return 0; }
转换函数进阶:
头文件conversion_function.h:
#pragma once #include<iostream> using namespace std; class Fraction { public: /*加上关键字explicit就代表告诉编译器说:你不要把double d2=f+4;这里面的4转换成Fraction哦! 我写的构造函数就只是为了构造对象,不用来充当转换函数的作用。注:关键字explicit%90多的几率 是加在构造函数的前面*/ explicit Fraction(int num, int den = 1) :m_numerator(num), m_denominator(den) { cout << "构造函数 被调用了哦!!!" << endl; } operator double() const { return double(this->m_numerator / this->m_denominator); } double operator +(const Fraction& f){ cout << "+号重载函数 被调用了哦!!!" << endl; return (this->m_numerator/this->m_denominator+f.m_numerator/f.m_denominator); } ~Fraction() { cout << "析构 函数被调用了哦!!!" << endl; } private: double m_numerator; double m_denominator; };
源文件conversion_function.cpp:
#include"conversion_function.h" int main() { Fraction f(3,5); double d2=f+4; cout << "d2: " << d2 << endl; system("pause"); return 0; }