我们用的最多的一般是从某类型到类类型之间的转换, 比如 Stone wolf; wolf = 3。这样的转换一般是通过构造函数来隐式转换,也就是Stone(int store)构造函数没有使用explicit关键字。那么如果我们想要 Stone wolf; double wo = wolf 这样的从类类型转换到其他类型,那么就需要使用C++的
转换函数了。
class Stone
{
public:
Stone(int stone):m_store(stone){ }
~Stone(){}
private:
int m_stone;
};
转换函数一般有如下限制:
- 转换函数必须是类方法,不能是友元函数之类的。
- 转换函数不能指定返回类型
- 转换函数不能有参数
例如,转换为 double 的原型为:
operator double();
下面举个例子,具体代码如下
//Stonewt.h
// Created by 陈国威 on 2018/3/25.
//
#ifndef C_PRIMER_PLUS_STONEWT_H
#define C_PRIMER_PLUS_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 //C_PRIMER_PLUS_STONEWT_H
//Stonewt.cpp
// Created by 陈国威 on 2018/3/25.
//
#include <iostream>
#include "Stonewt.h"
using namespace std;
Stonewt::Stonewt (double lbs)
{
stone = int (lbs);
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;
}
//stone1.cpp
// Created by 陈国威 on 2018/3/25.
//
#include <iostream>
#include "Stonewt.h"
using namespace std;
int main(void)
{
Stonewt poppins(9, 2.8);
double p_wt = poppins;
cout << "Convert to double =>";
cout << " Poppins: " << p_wt << " pounds.\n";
cout << "Convert to int => ";
cout << " Popins: " << int(poppins) << " pounds\n";
return 0;
}
注意,转换函数和构造函数一样也会隐式转换,比如下面的例子:
int ar[20];
...
Stonewt temp(14, 4);
...
int Temp = 1;
...
cout << ar[temp] << "!\n";
你一不小心,把 Temp 写成了temp, 那么这样的代码,编译器是通过的,并成功运行。因此为了避免这样的意想不到的错误,我们可以用关键字 explicit 作用于转换函数上。