【足迹C++primer】49、重载,转换,运算符

重载,转换,运算符

Conversion Operators
转换操作符

operator type() const
Conversions to
an array or a function type are not permitted.
转换函数必须是成员函数,不能指定返回 类型,必须有一个空的参数列表。
函数通常应 const。


Defining a Class with a Conversion Operator(献给热爱英语的朋友偷笑

定义一个类,表示一个在0到255范围类的一个整数
class SmallInt
{
public:
    SmallInt(int i=0):val(i)
    {
        if(i<0 || i>255)
            throw std::out_of_range("越界!!!越界进球无效!");
    }
    explicit operator int() const {return val;}  //转换操作符,不能有参数,是成员函数,没有返回类型
private:
    size_t val;
};

实现以下:
void fun1()
{
    SmallInt si;
    si=4;   //吧4隐式转换成SmallInt类型
//    si+3;   //隐式转换si为int类型,由于explicit这里会出错,加了explicit之后只能显式转换
}

Conversion Operators Can Yield Suprising Results
重载操作符能产生惊人的结果

void fun2()
{
    int i=42;
//    cin<<i;   this code would be legal if the conversion to bool were not explicit!

}

说是这样说但是到底有什么惊人的效果,反正我是没感觉!

explicit Conversion Operators
明确转换操作

说白了就是叫我们使用explicit来使用!

全代码!这次就简洁点哈哈!

/**
* 功能:重载,转换,运算符
* 时间:2014年7月19日15:05:21
* 作者:cutter_point
*/

#include<iostream>
#include <stdexcept>

using namespace std;

/**************************************
Conversion Operators
转换操作符
**************************************/
/*
operator type() const
Conversions to
an array or a function type are not permitted.
转换函数必须是成员函数,不能指定返回 类型,必须有一个空的参数列表。
函数通常应 const。
*/
/**
Defining a Class with a Conversion Operator
*/
//定义一个类,表示一个在0到255范围类的一个整数
class SmallInt
{
public:
    SmallInt(int i=0):val(i)
    {
        if(i<0 || i>255)
            throw std::out_of_range("越界!!!越界进球无效!");
    }
    explicit operator int() const {return val;}  //转换操作符,不能有参数,是成员函数,没有返回类型
private:
    size_t val;
};

void fun1()
{
    SmallInt si;
    si=4;   //吧4隐式转换成SmallInt类型
//    si+3;   //隐式转换si为int类型,由于explicit这里会出错,加了explicit之后只能显式转换
}

/**
Conversion Operators Can Yield Suprising Results
重载操作符能产生惊人的结果
*/
void fun2()
{
    int i=42;
//    cin<<i;   this code would be legal if the conversion to bool were not explicit!

}

/**
explicit Conversion Operators
明确转换操作
*/

//说白了就是叫我们使用explicit来使用!



int main()
{
    return 0;
}

我来说一下,人活在这世界上肯定会遭遇很多不幸和痛苦,而且一般这种不幸的事从来都不是一个一个来的,他们会在你措手不及的时候一下子全来了,就像精明的猎人,在你露出破绽的一瞬间把全部的活力倾泻在你的身上,确保万无一失。
每个人不可能一辈子都不犯错,但是当厄运来临的时候我们要时刻准备好,不要惊慌失措,冷静下来,好好想一想你应该如何去面对!






  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值