C 中的EXPLICIT关键字
- 格式:pdf
- 大小:109.16 KB
- 文档页数:9
endl换行符,也是std成员函数4).io流运算cout控制台输出—屏幕上终端窗口,带缓冲<<插入运算符cin控制台输入—键盘>>提取运算符5).名字空间Std:标准c++库所提供一切函数、对象、类型都隶属于std名字空间。
::-作用域限定符---名字空间“的”某个对象。
+= -=名字冲突:看作用域。
同一作用域不可使用相同名字。
----解决方法:成员前加名字空间名,中间::3.名字空间namespace 名字空间名{名字空间成员1;名字空间成员2;//名字空间成员可以是变量、函数、类型}名字空间名::名字空间成员1名字空间合并:同一个名字空间可以分别书写在不同的namespace子句中,只要它们的名字相同,仍然会被编译器识别为同一个名字空间。
Namespace名字空间名{名字空间成员1;}namespace名字空间名{名字空间成员2;}名字空间成员的声明和定义可以分开写,但是定义部分需要借助作用域限定符“::”指明所定义的成员隶属于哪个名字空间。
名字空间指令:using namespace名字空间名;名字空间指令以后的代码,对名字空间中的所有成员可见,可以直接引用,无需作用域限定符。
使用时要注意不要引入新的名字冲突。
名字空间声明:using名字空间名::名字空间成员;名字空间声明用于将名字空间中的特定标识符引入当前作用域,可以省略作用域限定符,直接引用之。
使用时注意不要因此引入新的名字冲突。
无名名字空间:不隶属于任何名字空间的标识符,编译器就将其缺省地放入无名名字空间。
对于无名名字空间中的成员,可以直接使用“::”进行访问。
名字空间允许多层嵌套,访问时需要逐层分解。
可利用名字空间别名简化名字空间嵌套路径的书写形式。
Using只能看里面一层。
4.结构、联合和枚举1)所有的类型关键字在声明变量时都可以省略。
struct Date{ //Date结构名int year; //成员变量(成员表列)(类型说明符成员名)int month;int day;void show(void)//成员函数{}};Int main(void){ //全局变量Date d = {2016,8,2},*e = &d;//e是指向d的指针d.show(); //“.”直接成员访问运算符e->show (); //“->”间接成员访问运算符return 0;}struct Date d = {2016,8,2};//C/C++Date d = {2016,8,2};//C++ //类型关键字省略2)C++中结构体可以包含函数(一个int四个字节,函数不放变量中,放代码区)成员函数的调用,前面要写“.”“->”定义结构体时不能同时初始化!3)C++中增加了匿名联合。
explicit 用法explicit关键字作用:禁止隐式调用类的单参数的构造函数。
上述实际上由两种情形:1. 禁止隐式调用拷贝构造函数2. 禁止类对象之间的隐式转换。
类对象间的隐式转换:利用一个已经存在的其他类型的对象来创建本类的新对象,且不显示调用本类的构造函数。
案例:#include <iostream>using namespace std;class A{public:A(){num = 9000;}A(int n){this->num = n;}A(const A&a){num = a.num;}friend void show(const A&);private:int num;};void show(const A& a){cout << "a.num = "<< a.num << endl;}int main(){// 隐式调用类A的单参的构造器cout << "Hello world!" << endl;A a1 = 5000;//调用隐式转换构造器A a2 = a1;//调用隐式拷贝构造器show(a1);show(a2);show(6000);return 0;}上述隐式调用C++语法是允许的,但很多人对这种表示方式不习惯,觉得程序的可读性较差。
为了禁止对类的单参数构造器的隐式调用,C++引入关键字explicit。
在类的定义中,在任何一个单参数构造器前加explicit,即可以禁止对该构造器的隐式调用。
案例:#include <iostream>using namespace std;class A{public:A(){num = 0;}explicit A(int n){this->num = n;}explicit A(const A& a){num = a.num;}friend void show(const A&);private:int num;};void show(const A& a){cout << " variable:" << a.num << endl;}int main(){//cout << "Hello world!" << endl;A a1(32);A a2(a1);show(a1);show(a2);show(A(6000));return 0;}这样程序既可以正常运行,并具有更好的可读性。
explicit的用法总结大全(学习版)编制人:__________________审核人:__________________审批人:__________________编制学校:__________________编制时间:____年____月____日序言下载提示:该文档是本店铺精心编制而成的,希望大家下载后,能够帮助大家解决实际问题。
文档下载后可定制修改,请根据实际需要进行调整和使用,谢谢!并且,本店铺为大家提供各种类型的经典范文,如英语单词、英语语法、英语听力、英语知识点、语文知识点、文言文、数学公式、数学知识点、作文大全、其他资料等等,想了解不同范文格式和写法,敬请关注!Download tips: This document is carefully compiled by this editor.I hope that after you download it, it can help you solve practical problems. The document can be customized and modified after downloading, please adjust and use it according to actual needs, thank you!In addition, this shop provides various types of classic sample essays, such as English words, English grammar, English listening, English knowledge points, Chinese knowledge points, classical Chinese, mathematical formulas, mathematics knowledge points, composition books, other materials, etc. Learn about the different formats and writing styles of sample essays, so stay tuned!explicit的用法总结大全explicit的意思adj. 明确的,清楚的,直言的,详述的,不隐瞒的变形:副词:explicitly;explicit用法explicit可以用作形容词explicit表示相当明确清晰,没有丝毫模棱两可或模糊不清。
C语言32个关键字及其含义auto:自动变量用关键字auto作存储类别的声明。
(可以省略,不写则隐含确定为“自动存储类别”)break:不能用于循环语句和switch语句之外的任何其他语句中。
作用为结束循环。
case :情况之一char:字符型const:常量continue:作用结束本次循环,不是终止整个循环。
default:默认结束do :做(先做后判断)double:双精度else:别的enum:枚举类型,extern:外部变量声明float:浮点型for:循环语句,goto:标记。
作用是从内层循环跳到外层循环。
if:如果,条件语句int:整型long:长整型register:寄存器标识符return:返回值short:短整型signed:有符号型sizeof:大小,xxstatic:静态的struct:结构体switch:交换typedef:起别名union:共用体unsigned:无符号型void:无返回C++66个关键字的中文含义1.asm(汇编),用法如下:asm (指令字符串);允许在C++程序中嵌入汇编代码。
2. auto(自动,automatic)是存储类型标识符,表明变量“自动”具有本地范围,块范围的变量声明(如for循环体内的变量声明)默认为auto存储类型。
3. bool(xx)类型,C++中的基本数据结构,其值可选为true(真)或者false(假)。
C++中的bool类型可以和int混用,具体来说就是0代表false,非0代表true。
bool类型常用于条件判断和函数返回值。
4. break(xx、跳出),用在switch语句或者循环语句中。
程序遇到break 后,即跳过该程序段,继续后面的语句执行。
5. case用于switch语句中,用于判断不同的条件类型。
6. catch catch和try语句一起用于异常处理。
7.char char(字符,character)类型,C++中的基本数据结构,其值一般为0~255的int。
c#转换关键词explicit的使用c#转换关键词explicit的使用引导语:C#适合为独立和嵌入式的系统编写程序,从使用复杂操作系统的大型系统到特定应用的小型系统均适用。
以下是店铺整理的c#转换关键词explicit的使用,欢迎参考阅读!explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符。
例如,在下面的示例中,此运算符将名为Fahrenheit 的类转换为名为 Celsius 的`类:C#// Must be defined inside a class called Farenheit:public static explicit operator Celsius(Fahrenheit f){return new Celsius((5.0f / 9.0f) * (f.degrees - 32));}可以如下所示调用此转换运算符:C#Fahrenheit f = new Fahrenheit(100.0f);Console.Write("{0} fahrenheit", f.Degrees);Celsius c = (Celsius)f;转换运算符将源类型转换为目标类型。
源类型提供转换运算符。
与隐式转换不同,必须通过强制转换的方式来调用显式转换运算符。
如果转换操作可能导致异常或丢失信息,则应将其标记为 explicit。
这可以防止编译器无提示地调用可能产生无法预见后果的转换操作。
省略此强制转换将导致编译时错误编译器错误 CS0266。
示例下面的示例提供 Fahrenheit 和 Celsius 类,它们中的每一个都为另一个提供显式转换运算符。
C#class Celsius{public Celsius(float temp){degrees = temp;}public static explicit operator Fahrenheit(Celsius c) {return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32); }public float Degrees{get { return degrees; }}private float degrees;}class Fahrenheit{public Fahrenheit(float temp){degrees = temp;}// Must be defined inside a class called Farenheit: public static explicit operator Celsius(Fahrenheit f) {return new Celsius((5.0f / 9.0f) * (f.degrees - 32));}public float Degrees{get { return degrees; }}private float degrees;}class MainClass{static void Main(){Fahrenheit f = new Fahrenheit(100.0f);Console.Write("{0} fahrenheit", f.Degrees);Celsius c = (Celsius)f;Console.Write(" = {0} celsius", c.Degrees);Fahrenheit f2 = (Fahrenheit)c;Console.WriteLine(" = {0} fahrenheit", f2.Degrees);}}/*Output:100 fahrenheit = 37.77778 celsius = 100 fahrenheit*/下面的示例定义一个结构Digit,该结构表示单个十进制数字。
C++中explicit的用法1. 介绍在C++编程中,explicit是一个关键字,用于修饰构造函数。
它的作用是禁止编译器执行自动类型转换,以避免意外的类型转换造成的不确定性和错误。
在本文中,将对explicit的用法进行详细介绍,并举例说明其在实际编程中的应用。
2. explicit的基本概念在C++中,当一个构造函数只接受一个参数时,它实际上定义了一个从该参数类型到类类型的隐式类型转换。
这种隐式类型转换可能会导致一些潜在的问题,比如不期望的类型转换或者不明确的代码逻辑。
为了解决这些问题,C++11引入了explicit关键字,用于显式声明构造函数为显式构造函数,从而禁止编译器执行隐式类型转换。
3. explicit的使用方法在类的构造函数声明前加上explicit关键字,即可将该构造函数声明为显式构造函数。
例如:```cppclass Test {public:explicit Test(int value) : m_value(value) {}private:int m_value;};```在上面的例子中,Test类的构造函数接受一个int类型的参数,但加上了explicit关键字,表示该构造函数为显式构造函数,禁止编译器执行隐式类型转换。
4. 显式构造函数的优势通过使用explicit关键字声明构造函数,我们可以有效地避免一些潜在的问题,例如:- 避免意外的类型转换:对于只接受一个参数的构造函数,如果不使用explicit关键字,那么它将成为隐式类型转换的候选函数,这可能导致意外的类型转换,从而产生错误的结果。
- 明确代码逻辑:显式构造函数可以使代码的逻辑更加明确,使得代码阅读和维护更加容易。
5. 显式构造函数的应用场景显式构造函数通常适用于以下情况:- 构造函数只接受一个参数,并且该参数不能被隐式转换为类的类型。
- 需要避免意外的类型转换和提高代码的可读性。
6. 总结在C++编程中,显式构造函数是一个非常有用的特性,它可以有效地避免一些潜在的问题,提高代码的可靠性和可维护性。
Qt中的关键字----explicit
关键字 explicit 可以禁⽌“单参数构造函数”被⽤于⾃动类型转换,主要⽤于 "修饰 "构造函数. 指明构造函数只能显⽰使⽤,⽬的是为了防⽌不必要的隐式转化.
关键字 explicit 可以禁⽌“单参数构造函数”被⽤于⾃动类型转换。
光看这⼀句似乎不太容易明⽩,下⾯,举个简单地例⼦。
//main.cpp
#include <iostream>
using namespace std;
class Test
{
public:
Test(int a)
{
m_data = a;
}
void show()
{
cout << "m_data = " << m_data << endl;
}
private:
int m_data;
};
void main(void)
{
Test t = 2; // 将⼀个常量赋给了⼀个对象
t.show();
}
编译能够通过,执⾏结果:m_data = 2。
为什么会这样呢?原来C++通过隐式转换,构造了⼀个临时对象Test(2),将它赋给了t(这⾥调⽤了默认的构造函数,⽽不是重载的“=”,因为这是在对象创建的时候)。
那么,如果给构造函数加上关键字 explicit ,构造函数变成了 explicit Test(int a),再次编译,编译器就会报错。
这时,就只能显式地使⽤构造函数了Test t = Test(2) 。
维基百科c++0x1.介绍C++0x(读作see plus plus oh ex)是c++编程语言预计的新标准的一个非正式名称。
今后会替换现有的c++标准,(ISO/IEC 14882)的这个1998年发布并在2003年更新的版本。
老版本可以通俗的叫做c++98和c++03。
新版本会添加一些语言核心内容和扩展c++标准库,将纳入c++技术报告库(C++ Technical Report 1 (TR1) libraries)-很可能不包含特殊的数学函数。
目前为止这个标准还未完成,这篇文章可能不能反映出最近的c++0x情况。
N3092的这个国际草案标准在2010年的3月被发布了。
ISO/IEC JTC1/SC22/WG21 c++标准委员会的计划是完成投票表决最后的委员会草案在2010年的8月,和在2011年的3月的标准会议上完善最后的国际草案标准。
不管怎样,WG21 预计到ISO官方发布标准会经历6个月到1年的时间,到这个标准的发行出版得到2011年末。
为了完成日程,委员会决定集中精力解决截至到2006年的问题而忽略新产生的决议。
c++这样的编程语言使用进化的方式改善和发展。
在c++发展的过程中用这样的方式必定会引起兼容以前代码的问题。
不管怎样,根据Bjarne Stroustrup(C + +语言的创作者和委员会的成员)的公告,新标准将“几乎百分之百的兼容现有的标准C + +".2.变更内容简介内容1 c++的版本变动即将标准更新2 扩展C + +的语言核心3 运行时核心语言的性能增强3.1右值引用(Rvalue reference)和移动语义(move semantics)3.2广义常量表达式(Generalized constant expressions)3.3修改旧数据的简单(plain)定义4 核心语言生成时的性能增强4.1外部模板(Extern template)5 核心语言可用性增强5.1初始化列表(Initializer lists)5.2统一初始化(Uniform initialization)5.3类型推断(Type inference)5.4范围为基础的循环(Range-based for-loop)5.5 lambda函数和表达式(Lambda functions and expressions)5.6替代函数的语法(Alternative function syntax)5.7对象的构造改进(Object construction improvement)5.8虚函数的显式重写(Explicit virtual function overrides)5.9空指针常量(Null pointer constant)5.10强类型枚举(Strongly typed enumerations)5.11尖括号(Angle bracket)5.12显式转换运算符(Explicit conversion operators)5.13别名模板(Template aliases)5.14无限制联合(Unrestricted unions)6 核心语言功能的改善6.1可变参数模板(Variadic templates)6.2新的字符串(New string literals)6.3用户定义的文字(User-defined literals)6.4复合内存模型(Multitasking memory model)6.5线程本地存储(Thread-local storage)6.6只能显式使用,违约的和删除了的特殊的成员函数(Explicitly-defaulted and deleted special member functions)6.7定义long long int(Type long long int)6.8静态断言(Static assertions)6.9允许sizeof对一个类,这个类中的成员没有指定明确的对象(Allow sizeof to work on members of classes without an explicit object)6.10允许垃圾收集的实现(Allow garbage collected implementations)7 C + +标准库的变化7.1升级到标准库组件(Upgrades to standard library components)7.3 Tuple类型(一个大小固定的异构对象集合)(Tuple types)7.4哈希表(Hash tables)7.5正则表达式(Regular expressions)7.6通用的智能指针(General-purpose smart pointers)7.7可扩展的随机数设施(Extensible random number facility)7.8包装参考(Wrapper reference)7.9函数对象多形性包装(Polymorphous wrappers for function objects)7.10元编程的type特性(Type traits for metaprogramming)7.11运行时返回函数对象类型的统一方法(Uniform method for computing the return type of function objects)8 计划取消或不包含的功能(Features planned but removed or not included)抹除了?9 要被移除或者弃用的特征(Features to be removed or deprecated)10 参见(See also)11 参考资料11.1 C + +标准委员会的文件11.2 文章(Articles)12 外部链接。
c++中的explicit关键字用来修饰类的构造函数,表明该构造函数是显式的,既然有"显式"那么必然就有"隐式",那么什么是显示而什么又是隐式的呢?如果c++类的构造函数有一个参数,那么在编译的时候就会有一个缺省的转换操作:将该构造函数对应数据类型的数据转换为该类对象,如下面所示:class MyClass{public:MyClass(int num);}....MyClass obj=10;//ok,convert int to MyClass在上面的代码中编译器自动将整型转换为MyClass类对象,实际上等同于下面的操作:MyClass temp(10);MyClass obj=temp;上面的所有的操作即是所谓的"隐式转换".如果要避免这种自动转换的功能,我们该怎么做呢?嘿嘿这就是关键字explicit的作用了,将类的构造函数声明为"显示",也就是在声明构造函数的时候前面添加上explicit即可,这样就可以防止这种自动的转换操作,如果我们修改上面的MyClass类的构造函数为显示的,那么下面的代码就不能够编译通过了,如下所示:class MyClass{public:explicit MyClass(int num);}....MyClass obj=10;//err,can‘t non-explict convertclass isbn_mismatch:public std::logic_error{public:explicit isbn_missmatch(const std::string &s):std:logic_error(s){}isbn_mismatch(const std::string&s,const std::string&lhs,const std::string &rhs):std::logic_error(s),left(lhs),right(rhs){}const std::string left,right;virtual~isbn_mismatch() throw(){}};Sales_item&operator+(const Sales_item&lhs,const Sales_item rhs){if(!lhs.same_isbn(rhs)) throw isbn_mismatch("isbn missmatch",lhs.book(),rhs.book());Sales_item ret(lhs);ret+rhs;return ret;}Sales_item item1,item2,sum;while(cinitem1item2){try{sun=item1+item2;}catch(const isbn_mismatch&e){cerre.what()"left isbn is:"e.left"right isbn is:"e.rightendl;}}用于用户自定义类型的构造函数,指定它是默认的构造函数,不可用于转换构造函数。
因为构造函数有三种:1拷贝构造函数2转换构造函数3一般的构造函数(我自己的术语^_^)另:如果一个类或结构存在多个构造函数时,explicit修饰的那个构造函数就是默认的class isbn_mismatch:public std::logic_error{public:explicit isbn_missmatch(const std::string &s):std:logic_error(s){}isbn_mismatch(const std::string&s,const std::string&lhs,const std::string &rhs):std::logic_error(s),left(lhs),right(rhs){}const std::string left,right;virtual~isbn_mismatch() throw(){}};Sales_item&operator+(const Sales_item&lhs,const Sales_item rhs){if(!lhs.same_isbn(rhs)) throw isbn_mismatch("isbn missmatch",lhs.book(),rhs.book());Sales_item ret(lhs);ret+rhs;return ret;}Sales_item item1,item2,sum;while(cinitem1item2){try{sun=item1+item2;}catch(const isbn_mismatch&e){cerre.what()"left isbn is:"e.left"right isbn is:"e.rightendl;}}这个《ANSI/ISO C++Professional Programmer‘s Handbook》是这样说的explicit ConstructorsA constructor that takes a single argument is,by default,an implicit conversion operator,which converts its argument toan object of its class(see also Chapter3,"Operator Overloading").Examine the following concrete example:class string{private:int size;int capacity;char*buff;public:string();string(int size);//constructor and implicit conversion operatorstring(const char*);//constructor and implicit conversion operator~string();};Class string has three constructors:a default constructor,a constructor that takes int,and a constructor thatconstructs a string from const char*.The second constructor is used to create an empty string object with aninitial preallocated buffer at the specified size.However,in the case of class string,the automatic conversion isdubious.Converting an int into a string object doesn ‘t make sense,although this is exactly what this constructor does.Consider the following:int main(){string s="hello";//OK,convert a C-string into a string objectint ns=0;s=1;//1oops,programmer intended to write ns=1,}In the expression s=1;,the programmer simply mistyped the name of the variable ns,typing s instead.Normally,the compiler detects the incompatible types and issues an error message.However,before ruling it out,the compiler firstsearches for a user-defined conversion that allows this expression;indeed,it finds the constructor that takes int.Consequently,the compiler interprets the expression s=1; as if the programmer had writtens=string(1);You might encounter a similar problem when calling a function that takes a string argument.The following examplecan either be a cryptic coding style or simply a programmer‘s typographical error.However,due to the implicitconversion constructor of class string,it will pass unnoticed:int f(string s);int main(){f(1);//without a an explicit constructor,//this call is expanded into:f(string(1));//was that intentional or merely a programmer‘s typo?}‘In order to avoid such implicit conversions,a constructor that takes one argument needs to be declared explicit:class string{//...public:explicit string(int size);//block implicit conversionstring(const char*);//implicit conversion~string();};An explicit constructordoes not behave as an implicit conversion operator,which enables the compiler to catch thetypographical error this time:int main(){string s="hello";//OK,convert a C-string into a string objectint ns=0;s=1;//compile time error;this time the compiler catches the typo}Why aren‘t all constructors automatically declared explicit?Under some conditions,the automatic type conversion isuseful and well behaved.A good example of this is the third constructor of string:string(const char*);The implicit type conversion of const char*to a string object enables its users to write the following:string s;s="Hello";The compiler implicitly transforms this intostring s;//pseudo C++ code:s=string("Hello");//create a temporary and assign it to sOn the other hand,if you declare this constructor explicit,you have to use explicit type conversion:class string{//...public:explicit string(const char*);};int main(){string s;s=string("Hello");//explicit conversion now requiredreturn0;}Extensive amounts of legacy C++code rely on the implicit conversion of constructors.The C++Standardizationcommittee was aware of that.In order to not make existing code break,the implicit conversion was retained.However,anew keyword,explicit,was introduced to the languageto enable the programmer to block the implicit conversionwhen it is undesirable.As a rule,a constructor that can be invoked with a single argument needs to be declaredexplicit.When the implicit type conversion is intentional and well behaved,the constructor can be used as animplicit conversion operator.网上找的讲的最好的贴:C++中explicit关键字的作用在C++中,如果一个类有只有一个参数的构造函数,C++允许一种特殊的声明类变量的方式。