C++ explicit关键字,修饰构造函数,ctor
2024-09-02 06:53:34
#include <iostream> // operator Type() 类型操作符重载
// operator int()
// operator double()
// ... ////////////////////////////////////////////////////////// class Rectangle
{
public:
#ifdef Want_compiler_to_add__function_of_int_2_Rectangle
Rectangle(const int w, const int h = 1)
: width(w), height(h)
{};
#else
explicit Rectangle(const int w, const int h = 1)
: width(w), height(h)
{};
#endif // Want_compiler_to_add__function_of_int_2_Rectangle ~Rectangle() {};
operator int(); // 重载 int() 之后,Rectangle就可以像一个int被使用。 public:
int width;
int height;
}; ////////////////////////////////////////////////////////// Rectangle::operator int()
{
return width * height;
} ////////////////////////////////////////////////////////// void
printInt(const int v)
{
std::cout << v+5 << std::endl;
} int
main()
{
Rectangle b = 10; // 这可以通过的原因是,调用了Rectangle的构造函数。编译器自动为int添加了转化为 Rectangle 的方法。但是有时候这不是我们想要的行为。
// 显式的为构造函数添加 explicit 就可以杜绝这种编译器的自动行为。
// 添加之后,该行就会报错。
return 0;
}
最新文章
- iOS10以及xCode8相关资料收集
- salesforce 零基础学习(三十二)通过Streams和DOM方式读写XML
- 分享一个我的JavaScript版GridView多功能表格
- Java 执行 SQL 脚本文件
- Compass 编译.scss文件的问题
- android NDK 实用学习(四)-类缓存
- [leetcode]二分查找总结
- 深入理解shared pool共享池之library cache系列二
- texedo 分布式事务
- dubbo源码分析二:服务发布
- Shell工具:jsondiff.sh
- 图表工具--- ECharts.js学习(一) 简单入门
- JUC中AQS简介
- SQL其他常用的语句
- BZOJ.5289.[AHOI/HNOI2018]排列(贪心 heap)
- MySQL主主复制(双主复制)配置过程介绍
- [原创]K8_Delphi源码免杀系列教程
- 简单易懂的程序语言入门小册子(1):基于文本替换的解释器,lambda演算
- javascript - ie - css - 动态更新鼠标指针形状
- Go 并发控制--WaitGroup的使用