c++新经典王建伟 自用 14.2.5 隐式转换

隐式转换 

与单参数构造函数密切相关

Time.hpp

//
//  Time.hpp
//  stud
//
//  Created by pt on 2024/4/8.
//

#ifndef Time_hpp
#define Time_hpp
//类声明
#include <iostream>
using namespace std;
class Time
{
public:
    int Hour;
    int Minute;
    int Second;

    Time(int tmphour);//单参数构造函数
};

#endif /* Time_hpp */

Time.cpp

Time::Time(int tmphour)//单参数构造函数的实现
{
    Hour = tmphour;
    Minute = 59;
    Second = 59;
}

main.cpp

#include <iostream>
#include "Time.hpp"
using namespace std;
int main()
{
   
    Time xx = 14;//合法 调用单参数构造函数 14->Time 这叫隐式转换 
    xx = 23;//临时对象 这句话也调用单参数构造函数,生成一个临时对象,把临时对象复制给xx 然后临时对象销毁
}

不管是单参数构造函数还是多参数构造函数都容易允许隐式转换

调用单参数构造函数产生的隐式转换:Time xx = 44; 

调用多参数构造函数产生的隐式转换: Time myTime5 = {12, 13, 52};

那么强制构造函数不做隐式转换,加explicit

Time.hpp

//
//  Time.hpp
//  stud
//
//  Created by pt on 2024/4/8.
//

#ifndef Time_hpp
#define Time_hpp
//类声明
#include <iostream>
using namespace std;
class Time
{
public:
    int Hour;
    int Minute;
    int Second;
    explicit Time(int tmphour, int tmpmin, int tmpsec);//构造函数
};

#endif /* Time_hpp */

Time.cpp

//
//  Time.cpp
//  stud
//
//  Created by pt on 2024/4/8.
//

#include "Time.hpp"
Time::Time(int tmphour, int tmpmin, int tmpsec)//构造函数的实现
{
    Hour = tmphour;
    Minute = tmpmin;
    Second = tmpsec;
}

main.cpp

#include <iostream>
#include "Time.hpp"
using namespace std;
int main()
{
   Time myTime5{12, 13, 52};//可
   Time myTime5 = {12, 13, 52};//不可

    /*在 C++ 中,当你在构造函数前加上 explicit 关键字时,你表明这个构造函数不能用于隐式类型转换,而只能用于显式类型转换。这意味着,该构造函数不能在需要隐式转换的上下文中被调用。

    让我们来看两个初始化对象的例子:
	Time myTime5{12, 13, 52}; 这是直接初始化的例子。在这种情况下,编译器使用花括号提供的参数直接调用构造函数,这是显式的,因此当构造函数标记为 explicit 时,这种初始化方式是允许的。
	Time myTime5 = {12, 13, 52}; 这是拷贝列表初始化。这里,编译器尝试使用花括号中的参数进行隐式类型转换,以创建一个 Time 对象,并将其赋值给 myTime5。但由于myTime5的构造函数被声明为 explicit,编译器不允许隐式转换,因此这种初始化方式是不允许的,将导致编译错误。
    总结来说,explicit 关键字阻止了构造函数在隐式类型转换中的使用。Time myTime5{12, 13, 52}; 是显式的直接初始化方式,而 Time myTime5 = {12, 13, 52}; 尝试进行隐式转换,所以后者在构造函数被声明为 explicit 时不被允许。
    */
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值