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++的更多相关文章

  1. Explicit keyword

    说实话,从来没有感觉到这个keyword实用,直到今天. explicit的意思是明显的,和它相相应的一个词是implicit意思是隐藏的. 我參考了MSDN和<c++标准程序库>对这个k ...

  2. C# 自己定义 implicit和explicit转换

    explicit 和 implicit 属于转换运算符,如用这两者能够让我们自己定义的类型支持相互交换explicti 表示显式转换.如从 A -> B 必须进行强制类型转换(B = (B)A) ...

  3. Explicit

    Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor ...

  4. explicit 构造函数

    一.构造函数.默认构造函数.合成的默认构造函数 构造函数,是函数名与类名同样.没有返回类型的特殊的成员函数.能够有初始化列表. 默认构造函数,没有形參.或全部形參都有默认实參的构造函数. 假设没有显示 ...

  5. C++ essentials 之 explicit constructor

    这篇博客的源起是我下面的一段代码 #include <bits/stdc++.h> using namespace std; int main(){ priority_queue<l ...

  6. Google C++ Style Guide

    Background C++ is one of the main development languages used by many of Google's open-source project ...

  7. 9.Methods(二)

    4.Operator Overload Methods allow a type to define how operators should manipulate instances of the ...

  8. Learn Python More

    0, 看了一个python项目开源源码, 才知道现在这点python知识实在是弱爆了.. 尼玛就像学了2500个常用汉字, 然后要去理解"楚辞".. 代码如下, 解释一点一点从网上 ...

  9. backref 用法

    源码 def backref(name, **kwargs): """Create a back reference with explicit keyword argu ...

随机推荐

  1. Java测试开发--sts安装Lombok(七)

    1.sts安装Lombok的步骤: 下载最新的lombok.jar包,进入cmd窗口,切到Lombok下载的目录,运行命令: java -jar lombok.jar,会出现如下界面: 已经默认选好了 ...

  2. Java多线程 | 02 | 线程同步机制

    同步机制简介 ​ 线程同步机制是一套用于协调线程之间的数据访问的机制.该机制可以保障线程安全.Java平台提供的线程同步机制包括: 锁,volatile关键字,final关键字,static关键字,以 ...

  3. Oracle system 用户无法登录问题

    新手刚用Oracle数据库时,可能会遇到system用户无法登录情况. 问题原因:1.可能输入默认密码时输入错误(比较低级,一般不会范). 2.可能你在安装的时候设置了密码,但是在登录的时候密码不正确 ...

  4. Python基础(类和实例)

    class Point(object): def __init__(self,name,score): self.__name = name self.__score = score def prin ...

  5. 菜鸡的Java笔记 第十七 static 关键字

    static 是java中定义的一个关键字,主要是描述全局的概念,所以利用static关键字可以定义属性,定义方法        但是在90%的情况下,我们的开发代码很少会去直接编写static*// ...

  6. [spojRNG]Random Number Generator

    先将所有数加上Ri,即变为区间[0,2Ri],考虑容斥,将区间容斥为[0,+oo)-[2Ri,+oo),然后对[2Ri,+oo)令$bi=ai-2Ri$,相当于范围都是[0,+oo)问题转化为求n个正 ...

  7. CKAD认证中的部署教程

    在上一章中,我们已经学会了使用 kubeadm 创建集群和加入新的节点,在本章中,将按照 CKAD 课程的方法重新部署一遍,实际上官方教程的内容不多,笔者写了两篇类似的部署方式,如果已经部署了 kub ...

  8. 前台json遍历拼装

    //添加角色. $.ajax({ type: "post", url: "/sysRole/list", data: {page: 1, limit: 1000 ...

  9. LOJ #6207 - 米缇(杜教筛+拉格朗日插值)

    LOJ 题面传送门 首先将 \(\sigma_k(ij)\) 展开: \[\sigma_k(ij)=\sum\limits_{x\mid i}\sum\limits_{y\mid j}[x\perp ...

  10. iTOL进化树调图细节记录

    目录 1. 注册 2. 去枝长 3. 加图例 4. 无根树颜色 5. 导出图片 iTOL基本用法已经会了,之前记录过一点:系统发育(进化)树绘制小结.最近重用,调图时又发现了些细节,记录下备忘. 1. ...