Explicit
Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Example is shown below.
namespace HW { /** * @class MoneyC * @brief */ class MoneyC { public: /** * @brief Constructor */ MoneyC(); /** * @brief Constructor */ explicit MoneyC(float iValue); /** * @brief Destructor */ ~MoneyC() = default; /** * @brief Set copy constructor as delete to prevent unintentional creation */ //MoneyC(const MoneyC& iValue) = delete; float GetAmount(void) const; /** * @brief Set copy constructor as delete to prevent unintentional creation */ MoneyC(const MoneyC& iValue) = delete; /** * @brief Set copy assignment as delete to prevent unintentional creation */ const MoneyC& operator=(const MoneyC& iValue) = delete; private: float mAmount; };
namespace HW { MoneyC::MoneyC():mAmount(1.0) { } MoneyC::MoneyC(float iValue):mAmount(iValue) { } float MoneyC::GetAmount(void) const { return this->mAmount; } } // end of namespace HW void DisplayMoneyInfo(const HW::MoneyC& iMoney) { std::cout << "The Amountt of Money is: "; std::cout << iMoney.GetAmount() << std::endl; } void MoneyTest(void) { std::cout << "===============MoneyTest()==================\n"; HW::MoneyC money1(4.99f); DisplayMoneyInfo(money1); DisplayMoneyInfo(4.99f); DisplayMoneyInfo((HW::MoneyC)7.99f); }
When compiling, the error will be indicated.
..\src\Learning.cpp:123:26: error: invalid initialization of reference of type 'const HW::MoneyC&' from expression of type 'float'
DisplayMoneyInfo(4.99f);
If remove the “explicit”, it can be compiled successful.
浙公网安备 33010602011771号