C++:关键字explicit的用法
2024-09-03 01:10:17
预测下面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
最新文章
- 丙申年把真假美猴王囚禁在容器中跑 ASP.NET Core 1.0
- C++基础练习题(一): 查找最短单词
- IOS第16天(1,Quartz2D基本图像绘制)
- Excel Sheet Column Number
- [CareerCup] 4.3 Create Minimal Binary Search Tree 创建最小二叉搜索树
- windows下添加mysql服务
- Uva 10007 / HDU 1131 - Count the Trees (卡特兰数)
- oracle 10g
- 虚拟化平台cloudstack新版本的调试
- Android中AlertDialog对话框禁止按[返回键]或[搜索键]
- MySQL 表的命令
- ajax--2017年1月15日
- ExcelUtil
- 关于ZendStudio 10.5的破解
- NSURLConnection从入门到放弃
- 现网环境业务不影响,但是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
- ACM-ICPC 2018 南京赛区网络预赛B
- 玩树莓派(raspberry pi) 2/3 raspbian的遇到的一些问题
- socket编程-阻塞和非阻塞
- MySQL 服务(mysqld)crash