C++11新特性之 explict
2022/2/2 14:12:58
本文主要是介绍C++11新特性之 explict,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
C++11新特性之 explict
- 目的
- 语法
- 代码示例
目的
指定构造函数或转换函数为显示,即不能用于隐式转化;
语法
一般出现在类定义之内的构造函数中;
如:
class P { explict P(){}; };
代码示例
#include <iostream> class Test { public: Test(int a):a_(a) { std::cout << "Test()" << std::endl; // 通过打印看调用几次构造函数 } int Get_Data() { return a_; } Test operator + (Test t) { return Test(a_ + t.a_); } private: int a_; }; int main() { Test t1{3}; Test t2 = t1 + 5; // 5 会隐式的调用的Test构造函数 std::cout << t2.Get_Data() << std::endl; //输出 8 }
在上一个的例子的基础之上加上 explict
#include <iostream> class Test { public: explicit Test(int a):a_(a) { std::cout << "Test()" << std::endl; // 通过打印看调用几次构造函数 } int Get_Data() { return a_; } Test operator + (Test t) { return Test(a_ + t.a_); } private: int a_; }; int main() { Test t1{3}; Test t2 = t1 + 5; //error // error: no match for 'operator+' (operand types are 'Test' and 'int') //说明 5 还是个int类型, 不能隐式的转化为Test }
explicit用于多个参数
#include <iostream> struct P { P(int a, int b) { std::cout << "P(int a, int b)" << std::endl; } explicit P(int a, int b, int c) { std::cout << "explicit P(int a, int b, int c)" << std::endl; } }; int main() { P p1(1,2); //OK P(int a, int b) P p2{1,2}; //OK P(int a, int b) P p3 = {1,2}; //OK P(int a, int b) P p4(1,2,3); //OK explicit P(int a, int b, int c) P p5{1,2,3}; //OK explicit P(int a, int b, int c) P p6 = {1,2,3}; //error:converting to 'P' from initializer list would use explicit constructor 'P::P(int, int, int) }
这篇关于C++11新特性之 explict的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26终极指南:Scrum中如何设置需求优先级
- 2024-06-26AI大模型企业应用实战(25)-为Langchain Agent添加记忆功能
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding
- 2024-06-23AI大模型企业应用实战(15)-langchain核心组件
- 2024-06-23AI大模型企业应用实战(16)-langchain核心组件
- 2024-06-23AI 大模型企业应用实战(06)-初识LangChain
- 2024-06-19EntBot.ai: AI Website Chatbot for Product Guides and Development Doc
- 2024-06-17zero-shot-learning-definition-examples-comparison
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享