C++ - 类中定义类型转换(type convertion) 详解

类中定义类型转换(type convertion)

 

本文地址: http://blog.csdn.net/caroline_wendy/article/details/15498591

 

类的转换操作符(conversion operator),形式:operator type() const; 意思是把ClassA->type; 即类中的成员变量输出为type类型;

注意型式中, 函数体没有声明返回值和参数, 但是函数体中需要返回(return)转换的值type;

type转换为ClassA, 则是通过ClassA的构造器(constructor)赋值, 间接得到, 但是保证类中只包含一个成员变量, 相当于type和成员变量之间的转换;

防止隐式(implicit)转换, 可以添加explicit限制词, 表示显示转换, 使用时, 需要添加static_cast<type>()操作;

使用explicit限制词,在整数类型中, 可以避免条件(condition)中的隐式转换, 如ClassA->type->bool进行转换,

可以在需要时, 使用显示转换, static_cast<type>(ClassA), 再默认由整型type转换为bool类型.

bool类型转换, 最好添加explicit, 可以阻止一些把bool类型当作整型的转换.

代码如下:

/*
 * CppPrimer.cpp
 *
 *  Created on: 2013.11.11
 *      Author: Caroline
 */

/*eclipse cdt*/

#include <iostream>
#include <stdexcept>
#include <cstddef>

using namespace std;

class SmallInt {
public:
	SmallInt(int i = 0) : val(i) { //int -> SmallInt
		if(i<0 || i>255)
			throw std::out_of_range("Bad SmallInt value");
		std::cout << "Hello, girl, this is int to SmallInt. " << std::endl;
	}
	explicit operator int() const { //SmallInt -> int, 显示
		std::cout << "Hello, girl, this is SmallInt to int. " << std::endl;
		return val;
	}
private:
	std::size_t val;
};

int main (void) {

	SmallInt si;
	si = 4;
	SmallInt si1 = 3.14;
	while(static_cast<int>(si1)) { //使用条件
		std::cout << "this is a condition" << std::endl;
		break;
	}

	return 0;

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值