在 C++ 中使用显式关键字
2022/1/31 1:06:26
本文主要是介绍在 C++ 中使用显式关键字,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
C++ 中的显式关键字用于标记构造函数以不隐式转换 C++ 中的类型。对于只接受一个参数并适用于构造函数(带有单个参数)的构造函数,它是可选的,因为它们是唯一可用于类型转换的构造函数。
让我们通过一个例子来理解显式关键字。
预测以下 C++ 程序的输出
// CPP Program to illustrate default // constructor without 'explicit' // keyword #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; } }; // Driver Code int main() { // a Complex object Complex com1(3.0, 0.0); if (com1 == 3.0) cout << "Same"; else cout << "Not Same"; return 0; }
输出
相同的
正如本文所讨论的,在 C++ 中,如果一个类有一个可以用单个参数调用的构造函数,那么这个构造函数就成为转换构造函数,因为这样的构造函数允许将单个参数转换为正在构造的类。
我们可以避免这种隐式转换,因为这些可能会导致意想不到的结果***。*** 我们可以借助显式关键字使构造函数显式化。例如,如果我们尝试使用带有构造函数的显式关键字的以下程序,则会出现编译错误。
// CPP Program to illustrate default // constructor with // 'explicit' keyword #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; } }; // Driver Code 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,但现在我们必须显式地对其进行类型转换。例如,以下程序可以正常工作。
// CPP Program to illustrate // default constructor with // 'explicit' keyword #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; } }; // Driver Code int main() { // a Complex object Complex com1(3.0, 0.0); if (com1 == (Complex)3.0) cout << "Same"; else cout << "Not Same"; return 0; }
输出
相同的
**注意:**显式说明符可以与常量表达式一起使用。但是,如果该常量表达式的计算结果为真,那么只有函数是显式的。
这篇关于在 C++ 中使用显式关键字的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升