Use of explicit keyword in C++
Predict the output of following C++ program.
1 #include <iostream>
2
3 using namespace std;
4
5 class Complex
6 {
7 private:
8 double real;
9 double imag;
10
11 public:
12 // Default constructor
13 Complex(double r = 0.0, double i = 0.0) : real(r), imag(i)
14 {
15 }
16
17 // A method to compare two Complex numbers
18 bool operator == (Complex rhs)
19 {
20 return (real == rhs.real && imag == rhs.imag)? true : false;
21 }
22 };
23
24 int main()
25 {
26 // a Complex object
27 Complex com1(3.0, 0.0);
28
29 if (com1 == 3.0)
30 cout << "Same";
31 else
32 cout << "Not Same";
33 return 0;
34 }
Output: The program compiles fine and produces following output.
Same
In C++, if a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows conversion of the single argument to the class being constructed.
We can avoid such implicit conversions as these may lead to unexpected results. We can make the constructor explicit with the help of explicit keyword.
For example, if we try the following program that uses explicit keyword with constructor, we get compilation error.
1 #include <iostream>
2 using namespace std;
3
4 class Complex
5 {
6 private:
7 double real;
8 double imag;
9
10 public:
11 // Default constructor
12 explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i)
13 {
14 }
15
16 // A method to compare two Complex numbers
17 bool operator== (Complex rhs)
18 {
19 return (real == rhs.real && imag == rhs.imag)? true : false;
20 }
21 };
22
23 int main()
24 {
25 // a Complex object
26 Complex com1(3.0, 0.0);
27
28 if (com1 == 3.0)
29 cout << "Same";
30 else
31 cout << "Not Same";
32 return 0;
33 }
Output: Compiler Error
no match for 'operator==' in 'com1 == 3.0e+0'
We can still typecast the double values to Complex, but now we have to explicitly typecast it.
For example, the following program works fine.
1 #include <iostream>
2 using namespace std;
3
4 class Complex
5 {
6 private:
7 double real;
8 double imag;
9
10 public:
11 // Default constructor
12 explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i)
13 {
14 }
15
16 // A method to compare two Complex numbers
17 bool operator== (Complex rhs)
18 {
19 return (real == rhs.real && imag == rhs.imag)? true : false;
20 }
21 };
22
23 int main()
24 {
25 // a Complex object
26 Complex com1(3.0, 0.0);
27
28 if (com1 == Complex(3.0))
29 cout << "Same";
30 else
31 cout << "Not Same";
32 return 0;
33 }
Output: The program compiles fine and produces following output.
Same
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-26 21:41:25
Use of explicit keyword in C++的更多相关文章
- Explicit keyword
说实话,从来没有感觉到这个keyword实用,直到今天. explicit的意思是明显的,和它相相应的一个词是implicit意思是隐藏的. 我參考了MSDN和<c++标准程序库>对这个k ...
- C# 自己定义 implicit和explicit转换
explicit 和 implicit 属于转换运算符,如用这两者能够让我们自己定义的类型支持相互交换explicti 表示显式转换.如从 A -> B 必须进行强制类型转换(B = (B)A) ...
- Explicit
Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor ...
- explicit 构造函数
一.构造函数.默认构造函数.合成的默认构造函数 构造函数,是函数名与类名同样.没有返回类型的特殊的成员函数.能够有初始化列表. 默认构造函数,没有形參.或全部形參都有默认实參的构造函数. 假设没有显示 ...
- C++ essentials 之 explicit constructor
这篇博客的源起是我下面的一段代码 #include <bits/stdc++.h> using namespace std; int main(){ priority_queue<l ...
- Google C++ Style Guide
Background C++ is one of the main development languages used by many of Google's open-source project ...
- 9.Methods(二)
4.Operator Overload Methods allow a type to define how operators should manipulate instances of the ...
- Learn Python More
0, 看了一个python项目开源源码, 才知道现在这点python知识实在是弱爆了.. 尼玛就像学了2500个常用汉字, 然后要去理解"楚辞".. 代码如下, 解释一点一点从网上 ...
- backref 用法
源码 def backref(name, **kwargs): """Create a back reference with explicit keyword argu ...
随机推荐
- Linux&C 线程控制 课后习题
Q1:多线程与多进程相比有什么优势? 多进程程序耗费的资源大,因为fork()的时候子进程需要继承父进程的几乎所有东西,但是多线程程序线程只继承一部分,即自己的私有数据,例如自己的线程ID,一组寄存器 ...
- 装了这几个IDEA插件,基本上一站式开发了!
前言 前几天有社区小伙伴私聊我,问我都用哪些IDEA插件,我的IDEA的主题看起来不错. 作为一个开源作者,每周要code大量的代码,提升日常工作效率是我一直追求的,在众多的IDEA插件中,我独钟爱这 ...
- VLAN技术 & ACL访问控制
VLAN介绍与配置 VLAN概述 交换网络中的问题 VLAN(Virtual Local Area Network) 在物理网络上划分出逻辑网 ,对应OS模型第二层 VLAN划分不受端口物理位置限制, ...
- 事件消息生产消费中间件-OSS.DataFlow
系统重构解耦的过程涉及不同领域服务分拆,或同一服务下实时响应部分和非响应部分分拆,分解后的各部分通过异步消息的流转传递,完成整体的业务逻辑,但是频繁的在业务层面直接调用不同消息队列的SDK,个人感觉不 ...
- Charles抓包 mock数据和rewrite功能
一.mock数据 mock:在后端返回异常或需要=改前端展示的数据时可以模拟返回的response 1.1 抓到接口后 右击保存response到本地,后缀改成.json打开可以看到是把json保存下 ...
- Django 小实例S1 简易学生选课管理系统 总目录
python Django实现的一个简易的教务选课系统. 介绍与演示的视频版本已发到我的b站: https://www.bilibili.com/video/BV1er4y1w7ty. 项目已上传到我 ...
- Typora常用命令
目录 Typora编辑器所用语法--Markdown 简介 1.Markdown --标题 2. Markdown --列表(子标题) 3. Markdown --列表嵌套 4. Markdown - ...
- ML2021 | (腾讯)PatrickStar:通过基于块的内存管理实现预训练模型的并行训练
前言 目前比较常见的并行训练是数据并行,这是基于模型能够在一个GPU上存储的前提,而当这个前提无法满足时,则需要将模型放在多个GPU上.现有的一些模型并行方案仍存在许多问题,本文提出了一种名为 ...
- 智能 Request 推荐,K8s 资源利用率提升 252%
作者 王孝威,FinOps 认证从业者,腾讯云容器服务产品经理,热衷于为客户提供高效的 Kubernetes 使用方式,为客户极致降本增效服务. 余宇飞,FinOps 认证从业者,腾讯云专家工程师,从 ...
- Codeforces 979E Kuro and Topological Parity(dp)
题面传送门 题意:有 \(n\) 个点,每个点要么被涂黑,要么被涂白,要么没有颜色. 现在你要: 给没有颜色的点图上颜色(黑色或白色) 在这 \(n\) 个点中连若干条有向边,可以不连通.但是只能从编 ...