类的 自动 和 强转

//*数字转对象      由单参数构造函数实现
//*关闭单参构造函数的自动强制转换特性          explicit

//*对象转数字 需要转换函数
//*1>转换函数必须是类方法 2>转换函数不能指定转换返回类型 3>转换函数没有参数
//*operater typename()  
ep:
operator double();
//////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////shonewt.h////////////////////////////////////////////////////////
#ifndef STONEWT_H_
#define STONEWT_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;
 operator int () const;
 operator double () const;
};

#endif
//////////////////////////////////////////////////////////////////////////////
////////////////////////shonewt.cpp///////////////////////////////////
#include <iostream>
using std::cout;
#include "shonewt.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=pds_left=pounds=0;
}

Stonewt::~Stonewt ()
{

}

void Stonewt::show_lbs() const
{
 cout<<stone<<" stone,"<<pds_left<<" pounds\n";
}

void Stonewt::show_stn() const
{
 cout<<pounds<<" pounds\n";
}

//conversion functions

Stonewt::operator int () const
{
 return int (pounds+0.5);
}

Stonewt::operator double () const
{
 return double (pounds);
}
/////////////////////////////////////////////////////////////////////////////
//////////////////main.cpp/////////////////////////////////////////////
#include <iostream>
#include "shonewt.h"

int main(void)
{
    using std::cout;
    Stonewt poppins(9,2.8);
 double p_wt=poppins;
 cout<<"convert to double=> ";
 cout<<"poppins: "<<p_wt<<" pounds.\n";
 cout<<"convert to int=> ";
 cout<<"poppins: "<<int (poppins)<<" poumds.\n";
 return 0;
}

posted @ 2007-02-19 02:53  Edward Xie  阅读(147)  评论(0编辑  收藏  举报