隐式转换
与单参数构造函数密切相关
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 时不被允许。
*/
}