类的自动转换和强制转换
只有一个参数的类构造函数用于将类型与该参数相同中的值转换为类类型
被称为转换函数的特殊类成员操作符函数,用于将类对象转换为其他类型
eg
全局对象(有文件作用域的对象)可实现
全局对象将在程序的main()函数被调用之前创建
只有一个参数的类构造函数用于将类型与该参数相同中的值转换为类类型
被称为转换函数的特殊类成员操作符函数,用于将类对象转换为其他类型
eg
stonewt1.h
#ifndef STONEWT1_H_ #define STONEWT1_H_ class Stonewt { private: enum{Lbs_per_stn = 14}; int stone; double pds_left; double pounds; public: Stonewt(double lbs); Stonewt(int stn,double lbs); Stonewt(); ~Stonewt(); void show_lbs()const; void show_stn()const; //conversion functions operator int()const; operator double()const; }; #endif
stone1.cpp
#include <iostream> using std::cout; #include "stonewt1.h" int main() { //调用 Stonewt(int stn,double lbs) Stonewt popins(9,2.8); double p_wt = popins; cout<<"Convert to double => "; cout<<"Popins: "<<p_wt<<" pounds.\n"; cout<<"Convert to int => "; cout<<"Popins: "<<int(popins)<<" pounds.\n"; system("pause"); return 0; }
stonewt2.cpp
main()函数之前调用Bootstrap#include <iostream> using std::cout; #include "stonewt1.h" Stonewt::Stonewt(double lbs) { stone = int(lbs)/Lbs_per_stn; pds_left = int(lbs)%Lbs_per_stn + lbs - int(lbs); pounds = lbs; } Stonewt::Stonewt(int stn,double lbs) { stone = stn; pds_left = lbs; pounds = stn*Lbs_per_stn + lbs; } Stonewt::Stonewt() { stone = pounds = pds_left = 0; } Stonewt::~Stonewt() { } void Stonewt::show_stn()const { cout<<stone<<" stone, "<<pds_left<<" pounds\n"; } void Stonewt::show_lbs()const { cout<<pounds<<" pounds\n"; } Stonewt::operator int()const { return int(pounds + 0.5); } Stonewt::operator double()const { return pounds; }
全局对象(有文件作用域的对象)可实现
全局对象将在程序的main()函数被调用之前创建