类中定义类型转换(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;
}