C++中构造函数如何用于从某种类型到类类型的转换
可以将类定义成与基本类型或另一个类相关,使得从一种类型转换为另一种类型是有意义的。在这种情况下,程序员可以指示C++如何自动进行转换,或通过强制类型转换来完成。为了说明这是如何进行的,我们将第3章中的磅转换为英石的程序改写成类的形式。首先,设计一种合适的类型。我们基本上是以两种方式(磅和英石)来表示重量的。对于在一个实体中包含一个概念的两种表示来说,类提供了一种非常好的方式。因此可以将重量的两种表示放在同一个类中,然后提供以这两种方式表达重量的类方法。程序清单 11.16提供了这个类的头文件。
// stonewt.h -- definition for the Stonewt class
#ifndef STONEWT_H_
#define STONEWT_H_
class Stonewt
{
private:
enum {Lbs_per_stn = 14}; // pounds per stone
int stone; // whole stones
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
正如第 10章指出的,对于定义类特定的常量来说,如果它们是整数,enum 提供了一种方便的途径。也可以采用下面这种方法:
static const int Lbs_per_stn = 14;
Stonewt类有3个构造函数,让您能够将Stonewt对象初始化为一个浮点数(单位为磅)或两个浮点数(分别代表英石和磅)。也可以创建 Stonewt对象,而不进行初始化:
Stonewt blossem(132.5); // weight = 132.5 pounds
Stonewt buttercup(10, 2); // weight=10 stone,2 pounds
Stonewt bubbles; // weight = default value
这个类并非真的需要声明构造函数,因为自动生成的默认构造函数就很好。参见【0voice C++】 另一方面,提供显式的声
明可为以后做好准备,以防必须定义构造函数另外,Stonewt类还提供了两个显示函数。一个以磅为单位来显示重量,另一个以英石和磅为单位来显示重量。程序清单 11.17列出了类方法的实现。每个构造函数都给这三个私有成员全部赋了值。因此创建Stonewt对象时,将自动设置这两种重量表示。
// stonewt.cpp -- Stonewt methods
#include <iostream>
using std::cout;
#include "stonewt.h"
// 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;
}
Stonewt::Stonewt() // default constructor, wt = 0
{
stone = pounds = pds_left = 0;
}
Stonewt::~Stonewt() // destructor
{
}
// 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";
}
因为 Stonewt对象表示一个重量,所以可以提供一些将整数或浮点值转换为 Stonewt对象的方法。我们已经这样做了!在C++中,接受一个参数的构造函数为将类型与该参数相同的值转换为类提供了蓝图。因此,下面的构造函数用于将 double类型的值转换为 Stonewt类型:
Stonewt(double lbs); // template for double-to-Stonewt conversion
也就是说,可以编写这样的代码:
Stonewt myCat; // create a Stonewt object
myCat = 19.6; // use Stonewt(double) to convert 19.6 to Stonewt
程序将使用构造函数 Stonewt(double)来创建一个临时的Stonewt对象,并将19.6作为初始化值。随后采用逐成员赋值方式将该临时对象的内容复制到 myCat 中。这一过程称为隐式转换,因为它是自动进行的,而不需要显式强制类型转换。
只有接受一个参数的构造函数才能作为转换函数。下面的构造函数有两个参数,因此不能用来转换类型:
Stonewt(int stn, double lbs); // not a conversion function
然而,如果给第二个参数提供默认值,它便可用于转换 int:
Stonewt(int stn, double lbs=0); // int-to-Stonewt conversion