Explicit Sepcifier

本文探讨了显式指定符(Explicit Specifier)在编程中的作用,特别是在转换构造函数中的影响。首先,解释了转换构造函数如何允许隐式类型转换,例如将两个double数值转化为复数对象,或者单个double数值进行转化。接着,指出通过在构造函数前添加显式指定符,可以阻止这种隐式转换,从而避免潜在的错误。最后,提到了显式类型转换(Explicitly Typecast)的使用情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Conversion Constructor

#include <iostream> 

using namespace std; 

class Complex 
{ 
private: 
	double real; 
	double imag; 

public: 
	// no default arguments -> a conversion 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; 
} 

Output: Same
Explanation: There are two implicit conversions happened in this code snippet.

  1. Complex com1 = {3.0, 0.0}; Use 2 double numbers to construct a complex object.
  2. if (com1 == 3.0) Use 1 double number to construct a complex object.

2. Explicit Specifier

If we add explicit before Constructor, we then will get an error.

class Complex 
{ 
private: 
	double real; 
	double imag; 

public: 
	// no default arguments -> a conversion 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; 
	} 
}; 

Output: error: chosen constructor is explicit in copy-initialization.

3. Explicitly Typecast

int main() 
{ 
	// a Complex object 
	Complex com1(3.0, 0.0); 

	if (com1 == static_cast<Complex>(3.0)) 
	cout << "Same"; 
	else
	cout << "Not Same"; 
	return 0; 
} 

Output: Same

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值