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");

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章