数可以进行类型隐式类型转换和强制类型转换
类能不能支持这种呢,正常是不支持的,但是可以通过构造函数将问题转换为,基本数据类型的隐式转换或强制类型转换
//stonewt.h -- definition for the stonewt class
#ifndef STONEWT_H_
#define STONEWT_H_
class Stonewt
{
private:
enum {Lbs_per_stn = 14}; //pouns per stone 转换因子
int stone; //whole stone 英石
double pds_left; //fractional pounds
double pounds; //entire weight in pounds 磅
public:
Stonewt(double lbs); //constructor for double pounds
Stonewt(int stn, double lbs); //constructor for stone,lbs
Stonewt(); //default constructor
~Stonewt();
void show_lbs()const; //show weight in pounds format
void show_stn()const; //show weight in stone format
};
#endif // !STONEWT_H_
//stonewt.cpp -- Stonewt methods
#include<iostream>
#include"stonewt.h"
using std::cout;
//construct Stonewt object from double value
Stonewt::Stonewt(double lbs)
{
stone = int(lbs) / Lbs_per_stn;//integer division
pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
pounds = lbs;
}
//construct Stonewt object from stone,double values
Stonewt::Stonewt(int stn,double lbs)
{
stone = stn;
pds_left = lbs;
pounds = stn * Lbs_per_stn + lbs;
}
//default construct Stonewt wt = 0
Stonewt::Stonewt()
{
stone = pounds = pds_left = 0;
}
//destructor
Stonewt::~Stonewt()
{
}
//show weight in stones
void Stonewt::show_stn()const
{
cout << stone << " stone, " << pds_left << " pounds\n";
}
//show weight in pounds
void Stonewt::show_lbs()const
{
cout << pounds << " pounds\n";
}
#pragma region 11.18.stone.cpp
程序清单
//stone.cpp -- user-defined conversions
#if 1
#include <iostream>
#include"stonewt.h"
using std::cout;
void display(const Stonewt& st, int n);
int main()
{
Stonewt incognito = 275;//uses constructor to initialize
Stonewt wolfe(285.7);//same as Stonewt wolfe = 285.7
Stonewt taft(21, 8);
cout << "The celebrity weighed ";
incognito.show_stn();
cout << "The detective weighed ";
wolfe.show_stn();
cout << "The President weighed ";
taft.show_lbs();
incognito = 276.8;
taft = 325;
cout << "After dinner,the clelbrity weighed ";
incognito.show_stn();
cout << "After dinner,the President weighed ";
taft.show_lbs();
display(taft, 2);
cout << "The wrestler weighed even more.\n";
display(422, 2);
cout << "No stone left unearned\n";
return 0;
}
void display(const Stonewt& st, int n)
{
int i;
for ( i = 0; i < n; i++)
{
cout << "Wow! ";
st.show_stn();
}
}