C++类的自动转换:类型转换函数

一、通常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
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值