一、通常C++中内置类型转换:
在C++中,将一个标准类型的变量 的 值 赋给 另一种标准类型的 变量时,如果这两种类型兼容,则C++自动将这个值转换为接收变量的类型。如:
long a = 11; //将11从int型转换为long类型
double b = 22; //将22从int型转换为double型
int c = 33.33; //将33.33从double型转换为int型,值变为33
二、类中的类型准换:
在C++中,仅仅 接受一个参数的 构造函数 被称为 类型转换函数。
若构造函数有多个参数,如果除了第一个参数外 的 其它参数 都有默认值,则 此构造函数 也是 类型转换函数。
类型转换函数 能够实现 参数类型 到 类类型 的自动转换(强制转换)。
构造函数用作 自动类型转换函数 的过程是 隐式转换。
//这种隐式转换存在风险,关键字explict用于关闭这种自动隐式转换特性。
类的定义示例:
//stonewt.h -- definition for the Stonewt class
#ifndef STONEWT_H_
#define STONEWT_H_
class Stonewt
{
private:
enum { Lbs_per_stn = 14 }; // pounds per stone,定义类特定的常量,如果常量是整数,enum方法
//static const int Lbs_per_stn = 14; //或者static方法,或者在构造函数初始化列表中赋值
int stone; // whole stones
double pds_left; // fractional pounds
double pounds; // entire weight in pounds
public:
Stonewt(double lbs); // 有一个double参数的构造函数
Stonewt(int stn, double lbs); // constructor for stone, lbs //没有显式声明explict
Stonewt(); // 默认无参构造函数
~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 namespace std;
//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;
cout << "一个double参数的Stonewt构造函数被调用!" << endl;
}
//construct Stonewt object from stone, double values
Stonewt::St