C++类的自动转换(explicit的用法)
作者:互联网
#include<iostream>
#include<iomanip>
class Stonewt
{
private:
enum {LBS_PER_STN = 14};
int stone;
double pds_left;
double pounds;
public:
explicit Stonewt(double lbs);
/*Stonewt(int stn, double lbs);
Stonewt();
~Stonewt();*/
operator double() const;
friend std::ostream & operator << (std::ostream & os, const Stonewt & t);
};
Stonewt::Stonewt(double lbs)
{
stone = int(lbs) / LBS_PER_STN;
pds_left = int(lbs) % LBS_PER_STN + lbs - int(lbs);
pounds = lbs;
}
std::ostream & operator << (std::ostream & os, const Stonewt & t)
{
os << t.stone << std::setw(10) << t.pounds << std::setw(3);
return os;
}
Stonewt::operator double() const
{
return 5.3;
}
int main()
{
/*Stonewt x = 3.5;*/
Stonewt x (3.5);
std::cout << x << std::endl;
double y = x;
std::cout << y << std::endl;
int z = x;
std::cout << z << std::endl;
system("pause");
}
标签:std,lbs,int,double,explicit,C++,用法,Stonewt,operator 来源: https://blog.csdn.net/qq_41614638/article/details/80525245