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 ...
随机推荐
- Maven快速入门(五)Maven的依赖管理
前面我们讲了maven项目中的最重要的文件:pom.xml 配置文件相关内容.介绍了pom 是如何定义项目,如何添加依赖的jar 包的等. 我们知道,在Maven的生命周期中,存在编译.测试.运行等过 ...
- Java经典面试题(二)-不古出品
@ 目录 1. 为什么说 Java 语言"编译与解释并存"? 2.Oracle JDK 和 OpenJDK 的对比? 3.字符型常量和字符串常量的区别? 4.Java 泛型了解么? ...
- dotnet templating 定制自己的项目模板
由于工作需要,研究了一下VS 项目模板生成的相关内容,本文做一下记录借助.NET Core Template Engine创建一个加单的项目模板. 创建项目代码和配置文件 首先创建一个Minimal ...
- 关于Python中用户输入字符串(与变量名相同)无法作为变量名引用的理解以及解决方案
在用户登录账号时,我需要在字典中查找是否存在其账号名称以及密码是否正确. 所以,我想将用户输入的账号赋值给变量,在字典中查找是否有此指值. 代码如下: 1 Ya = {'姓名': 'Ya', 'pas ...
- Mac 下 Nginx 配置使用
安装 homebrew /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/m ...
- Django笔记&教程 3-4 模板继承
Django 自学笔记兼学习教程第3章第4节--模板继承 点击查看教程总目录 在介绍具体的技术之前,先介绍在什么样的场景中,需要使用这样的技术,我觉得这对于新手理解起来很重要. 一般来说,要渲染一个页 ...
- dedecms被挂马排毒的过程
又经历了一次dedecms被挂马排毒的过程,排毒过程在这里跟大家分享一下. 挂马之后,网站的表现形式: 直接访问网站没有任何问题,从百度搜索的关键词访问网站,就跳转到另外一个网站. 根据我原来的排毒经 ...
- [cf1479E]School Clubs
对于当前班级状态$S$,定义一个函数$\varphi(S)$,要求其满足: 令结束状态为$S_{end}$,对于任意$S\ne S_{end}$,若其下一个状态为$S'$,则$E(\varphi(S) ...
- 【IDEA】头注释和方法注释
头注释和方法注释 2020-09-08 10:16:17 by冲冲 1.头注释 ①设置 ②模板内容 /** * @ClassName ${NAME} * @Description ${DESCRI ...
- 从零开始学Kotlin第一课
Kotlin的方法: 一个简单的计算器: fun main(args:Array<String>){ //主函数main方法 var a=8; var b=9; println(plus( ...