隐式转换与explicit关键字
来源:互联网 发布:武大樱花 知乎 编辑:程序博客网 时间:2024/06/16 08:42
{
public:
int mage;
Person()
{
cout << "无参构造" << endl;
}
Person(const int age)
{
mage = age;
cout << "有参构造" << endl;
}
};
int main()
{
Person person = 1;//隐式转换,Person person=Person(10)
system("pause");
return 0;
}
上述代码能够正常运行。
class Person
{
public:
int mage;
Person()
{
cout << "无参构造" << endl;
}
Person(const int age)
{
mage = age;
cout << "有参构造" << endl;
}
Person(const int age, int b = 0)
{
cout << "默认参数构造" << endl;
}
};
int main()
{
Person person = 1;//隐式转换,Person person=Person(10)
system("pause");
return 0;
}
上述代码不能正常运行,生成可执行程序时,会报错:无法从int转换到Person。
也就是说,编译器不能进行隐式转换。因为,编译器不知道是调用Person(const int age),还是调用Person(const int age,int b=0)。
将Person(const int age)前加explicit关键字修饰:
class Person
{
public:
int mage;
Person()
{
cout << "无参构造" << endl;
}
explicit Person(const int age)
{
mage = age;
cout << "有参构造" << endl;
}
Person(const int age, int b = 0)
{
cout << "默认参数构造" << endl;
}
};
告知编译器Person(const int age)不进行隐式转换,则编译器只能调用Person(const int age,int b=0),进行隐式转换。
- 隐式转换与explicit关键字
- C++ 隐式类型转换与关键字explicit
- C++ 隐式类型转换与关键字explicit
- C++ explicit关键字(隐式转换)
- explicit 隐式转换与显示转换
- 从Qt谈到C++(一):关键字explicit与隐式类型转换
- .net转换关键字:operator、explicit与implicit
- 构造函数自动转换与explicit关键字
- 隐式类型转换和explicit关键字的作用
- c++中的explicit关键字及隐式类型转换
- c++中的explicit关键字及隐式类型转换
- 隐式类型转换和explicit关键字的作用
- 隐式类型转换和explicit关键字的作用
- c++中的explicit关键字及隐式类型转换
- c++中的explicit关键字及隐式类型转换
- C++中的explicit关键字 抑制隐式转换
- C++类的 explicit 关键字和隐式转换
- C++中的explicit关键字 抑制隐式转换构造
- dict--review python
- view跟ViewGroup时间分发机制笔记整理
- 杂花生树(三十八)
- 购物车
- SpringMVC静态资源访问问题
- 隐式转换与explicit关键字
- WebView与JS的那些事: 注入JS去除悬浮广告
- Apache中更改PHP版本型号
- Writing Clear Code
- 毕业论文如何做到查重率为6%以下?
- Java 遍历json
- 深入解析:分布式系统的事务处理经典问题及模型
- webrtc交叉编译
- PHP框架开发一(首言)