C/C++编程笔记:在C++中使用显式关键字

首先,我们看一看下面这个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 0;
}
输出:程序编译正常,并产生以下输出。
Same
在C ++中,如果类具有可以用单个参数调用的构造函数,则该构造函数将成为转换构造函数,因为这样的构造函数允许将单个参数转换为正在构造的类。
我们可以避免这种隐式转换,因为它们可能导致意外的结果。例如,如果尝试下面的程序,该程序使用带有构造函数的显式关键字,则会出现编译错误。
#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 0;
}
输出:编译器错误
在'com1 == 3.0e + 0'中找不到'operator =='的匹配项
我们仍然可以将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 0;
}
输出:程序编译正常,并产生以下输出。
Same
以上就是今天的全部内容了。每日分享小知识,希望对你有帮助~
另外如果你想更好的提升你的编程能力,学好C语言C++编程!弯道超车,快人一步!笔者这里或许可以帮到你~
微信公众号:C语言编程学习基地
分享(源码、项目实战视频、项目笔记,基础入门教程)
欢迎转行和学习编程的伙伴,利用更多的资料学习成长比自己琢磨更快哦!


