#include <iostream>
using namespace std;
class Person
{
public:
Person();
// explicit Person(const int &_name);//静止隐式类型转化。通俗一点就是不能用=,或者产生临时变量的时候也会是隐式类型转化
Person(const Person &other);
Person(const int &_name);//可以把int类型转化为Person类型
int name;
};
Person::Person() : name(-1)
{
cout << "默认构造函数" << endl;
}
Person::Person(const int &_name) : name(_name)
{
cout << "int隐式类型转化拷贝构造函数" << endl;
}
Person::Person(const Person &other) : name(other.name)
{
cout << "拷贝构造函数" << endl;
}
int main(int argc, const char *argv[])
{
Person p3 = 10;//10赋值的时候会产生临时对象调用构造函数,再将临时对象赋给p3 ,加编译选项
//就能强制显示调用了构造函数,如果把explicit那行注释去掉就会报错
cout << p3.name << endl;
return 0;
}
c++ explicit 禁止隐式类型转换
于 2023-03-27 19:13:25 首次发布