预测下面C++程序的输出:

#include <iostream> 

using namespace std; 

class Complex
{
private:
double real;
double imag; public:
// Default constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} // A method to compare two Complex numbers
bool operator == (Complex rhs) {
return (real == rhs.real && imag == rhs.imag)? true : false;
}
}; int main()
{
// a Complex object
Complex com1(3.0, 0.0); if (com1 == 3.0)
cout << "Same";
else
cout << "Not Same";
return ;
}

输出:编译通过,产生输出。

Same

在C++中,如果一个类有一个可以用单个参数调用的构造函数,那么这个构造函数就变成了转换构造函数,因为这样的构造函数允许将单个参数转换成正在构造的类。 我们可以避免这种隐式转换,因为这可能会导致意想不到的结果。我们可以借助explicit使构造函数显式化。例如,如果我们尝试下面的程序,在构造函数中使用显式关键字,我们会得到编译错误。
#include <iostream> 

using namespace std; 

class Complex
{
private:
double real;
double imag; public:
// Default constructor
explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} // A method to compare two Complex numbers
bool operator== (Complex rhs) {
return (real == rhs.real && imag == rhs.imag)? true : false;
}
}; int main()
{
// a Complex object
Complex com1(3.0, 0.0); if (com1 == 3.0)
cout << "Same";
else
cout << "Not Same";
return ;
}

输出:编译错误。

no match for 'operator==' in 'com1 == 3.0e+0'

我们仍然可以将double类型转换为Complex类型,但是现在我们必须要明确对它进行类型转换。例如,下面这个程序就工作正常。

#include <iostream> 

using namespace std; 

class Complex
{
private:
double real;
double imag; public:
// Default constructor
explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} // A method to compare two Complex numbers
bool operator== (Complex rhs) {
return (real == rhs.real && imag == rhs.imag)? true : false;
}
}; int main()
{
// a Complex object
Complex com1(3.0, 0.0); if (com1 == (Complex)3.0)
cout << "Same";
else
cout << "Not Same";
return ;
}

输出:编译通过,产生输出。

Same

 
 

最新文章

  1. 丙申年把真假美猴王囚禁在容器中跑 ASP.NET Core 1.0
  2. C++基础练习题(一): 查找最短单词
  3. IOS第16天(1,Quartz2D基本图像绘制)
  4. Excel Sheet Column Number
  5. [CareerCup] 4.3 Create Minimal Binary Search Tree 创建最小二叉搜索树
  6. windows下添加mysql服务
  7. Uva 10007 / HDU 1131 - Count the Trees (卡特兰数)
  8. oracle 10g
  9. 虚拟化平台cloudstack新版本的调试
  10. Android中AlertDialog对话框禁止按[返回键]或[搜索键]
  11. MySQL 表的命令
  12. ajax--2017年1月15日
  13. ExcelUtil
  14. 关于ZendStudio 10.5的破解
  15. NSURLConnection从入门到放弃
  16. 现网环境业务不影响,但是tomcat启动一直有error日志,ERROR org.apache.catalina.startup.ContextConfig- Unable to process Jar entry [module-info.class] from Jar [jar:file:/home/iufs/apache-tomcat/webapps/iufs/WEB-INF/lib/asm
  17. ACM-ICPC 2018 南京赛区网络预赛B
  18. 玩树莓派(raspberry pi) 2/3 raspbian的遇到的一些问题
  19. socket编程-阻塞和非阻塞
  20. MySQL 服务(mysqld)crash

热门文章

  1. python 爬虫 urllib模块 url编码处理
  2. lua编译器和ide
  3. Linux 概念与快捷方式
  4. 编写java 程序与Linux进行远程连接并运行linux下的脚本
  5. 【2019V2全新发布】ComponentOne .NET开发控件集,新增.NET Core数据引擎
  6. 纯前端表格控件SpreadJS V12.1 隆重登场,专注易用性,提升用户体验
  7. springboot整合springdatajpa时jar冲突
  8. 使用php过滤emoji表情
  9. poj 4005 Moles
  10. Sleepy Game CodeForces - 936B