2.将某个值赋值某个对象。
3.将某值传递给接收某对象参数的函数时。
4.返回值被声明为某个对象的函数返回一个某值时。
5.以上情况中,如果另一个值可以转化为某值时。
使用explicit关键字可以强制使用显式构造函数,可以避免把某值转化为某对象。
如果想进行相反的转换,那么就需要使用C++操作符函数-------转换函数。转换函数是用户自定义的强制类型转换。使用转换函数得注意以下三点:
1.转换函数必须是类方法。
2.转换函数不能指定返回类型。
3.转换函数不能有参数。
同样的,也上三段代码。
stonewt.h
[cpp]
#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
stonewt.cpp
[cpp]
#include
using std::cout;
#include "stonewt.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;
}
stone.cpp
[cpp]
#include
using std::cout;
#include "stonewt.h"
void display(const Stonewt st, int n);
int main()
{
Stonewt pavarotti = 260; //调用构造函数,因为260能转化为浮点型
Stonewt wolfe(285.7); //类似Stonewt wolfe = 285.7;
Stonewt taft(21,8);
cout << "The tenor weighted ";
pavarotti.show_stn();
cout << "THe detective weighted ";
wolfe.show_stn();
cout << "The President weighed ";
taft.show_lbs();
pavarotti = 256.8; //构造函数进行初始化
taft = 325; //和 taft = Stonewt(325);一样
cout << "After dinner, the tenor weighed ";
pavarotti.show_stn();
cout << "After dinner, the president weighed ";
taft.show_lbs();
display(taft, 2);
cout << "The wrestler weighted even more.\n";
display(422, 2); //将422转化乘 Stonewt对象
cout << "No stone left unearned\n";
// 使用转换函数将类对象转化为基本类型
Stonewt poppins(9, 28);
double p_wt = poppins;
cout << "COnvert to double => ";
cout << "Poppins: " << p_wt << " pounds.\n";
cout << "Convert to int => ";
cout << "Poppins: " << int(poppins) << " pounds.\n";
return 0; www.2cto.com
}
void display(const Stonewt st, int n)
{
for (int i = 0; i < n; i++)
{
cout << "Wow! ";
st.show_stn();
}
}
作者:Paul_wuhaha