//demo.cpp
#include <iostream>
#include <string>
class Demo{
public:
Demo(const std::string& str):age(0),name(str)
{}
Demo(int i):age(i),name("null"){}
public:
int age;
std::string name;
};
int main()
{
Demo b = 12;
Demo a = "zhangsan";
//应该转为:Demo a = std::string("zhangsan");
}
b可以正常初始化,a不可以。
因为这条语句做了两次隐式类型转换,一次是const char *转为string,再一次是string转为Demo。
explicit关键字
作用:禁止隐式类型转换
//demo.cpp
#include <iostream>
#include <string>
class Demo{
public:
Demo(const std::string& str):age(0),name(str)
{}
explicit Demo(int i):age(i),name("null"){}
public:
int age;
std::string name;
};
int main()
{
Demo b = 12;
Demo a = std::string("zhangsan");
}
//b不能转换,a可以