explicit关键字的含义和用法

合集下载

explicit和implicit的含义

explicit和implicit的含义

explicit 和 implicit 属于转换运算符,如用这两者可以让我们自定义的类型支持相互交换explicti 表示显式转换,如从 A -> B 必须进行强制类型转换(B=(B)A)implicit 表示隐式转换,如从 B -> A 只需直接赋值(A=B)隐式转换可以让我们的代码看上去更漂亮、更简洁易懂,所以最好多使用implicit 运算符。

不过!如果对象本身在转换时会损失一些信息(如精度),那么我们只能使用 explicit 运算符,以便在编译期就能警告客户调用端示例:using System;using System.Collections.Generic;using System.Text;namespace Example23{class Program{//本例灵感来源于大话西游经典台词“神仙?妖怪?”–主要是我实在想不出什么好例子了class Immortal{public string name;public Immortal(string Name){name=Name;}public static implicit operator Monster(Immortal value){return new Monster( + “:神仙变妖怪?偷偷下凡即可。

”);}}class Monster{public string name;public Monster(string Name){name=Name;}public static explicit operator Immortal(Monster value){return new Immortal( + “:妖怪想当神仙?再去修炼五百年!”);}}static void Main(string[] args){Immortal tmpImmortal=new Immortal(“紫霞仙子”);//隐式转换Monster tmpObj1=tmpImmortal;Console.WriteLine();Monster tmpMonster=new Monster(“孙悟空”); //显式转换Immortal tmpObj2=(Immortal)tmpMonster; Console.WriteLine(); Console.ReadLine();}}}结果:紫霞仙子:神仙变妖怪?偷偷下凡即可。

构造函数explicit

构造函数explicit

构造函数explicit在C++中,可以使用关键字`explicit`来修饰一个类的构造函数,以防止隐式类型转换。

`explicit`构造函数要求用户必须使用显式转换来调用构造函数。

本文将详细介绍`explicit`构造函数的作用、用法、注意事项以及示例。

## 1. `explicit`构造函数的作用`explicit`关键字可以用于修饰类的单参数构造函数,这样做的目的是为了避免隐式类型转换。

当构造函数被声明为`explicit`时,只能通过显式转换来调用该构造函数,不允许进行隐式的类型转换。

隐式类型转换可能导致一些未预料的行为,降低代码的可读性和可维护性。

因此,在一些情况下,使用`explicit`关键字来限制隐式类型转换是一种良好的编程实践。

## 2. `explicit`构造函数的用法使用`explicit`修饰构造函数的语法如下所示:```cppexplicit 类名(参数列表) { ... }```需要注意的是,`explicit`只能修饰单参数的构造函数,不能用于默认构造函数或多参数构造函数。

当类的构造函数被声明为`explicit`时,在实例化该类对象时,必须使用显式转换来调用构造函数,否则编译器将会报错。

## 3. `explicit`构造函数的注意事项以下是使用`explicit`构造函数时需要注意的几点事项:###3.1避免隐式类型转换使用`explicit`构造函数可以避免隐式类型转换,明确地告诉编译器不进行隐式转换。

这样做可以提高代码的可读性和可维护性。

###3.2无法进行隐式类型转换一旦构造函数被声明为`explicit`,将无法进行隐式类型转换。

编译器会拒绝隐式的转换操作。

###3.3需要显式转换在实例化对象时,由于构造函数被声明为`explicit`,所以必须使用显式转换来调用构造函数。

这样可以增加代码的清晰度,并避免一些潜在的问题。

###3.4适用范围`explicit`构造函数通常在类型之间存在其中一种逻辑上的不兼容性时使用,通过限制隐式转换来加强类型检查。

c++中 explicit关键字的含义和用法

c++中 explicit关键字的含义和用法

上面的所有的操作即是所谓的"隐式转换".
如果要避免这种自动转换的功能,我们该怎么做呢?嘿嘿这就是关键字explicit的作用了,将类的构造函数声明为"显示",也就是在声明构造函数的时候 前面添加上explicit即可,这样就可以防止这种自动的转换操作,如果我们修改上面的MyClass类的构造函数为显示的,那么下面的代码就不能够编 译通过了,如下所示:
{
public:
MyClass( int num );
}
....
MyClass obj = 10; //ok,convert int to MyClass
在上面的代码中编译器自动将整型转换为MyClass类对象,实际上等同于下面的操作:
MyClass temp(10);
MyClass obj = temp;
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;}
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 requiredreturn 0;}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.

explicit 用法

explicit 用法

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;}这样程序既可以正常运行,并具有更好的可读性。

c语言的32个关键字及其含义

c语言的32个关键字及其含义

c语言的32个关键字及其含义C语言是一门广泛应用于计算机编程的高级编程语言,其简洁、高效的特点使之成为许多程序员的首选。

而C语言的关键字则是构成C语言语法结构的基石,掌握这些关键字的含义对于编写高质量的C代码至关重要。

本文将会介绍C语言的32个关键字及其含义。

一、自动变量(auto)auto关键字用于声明自动变量,自动变量是在代码块中定义的变量。

它们的生命周期仅限于所在代码块,函数的参数也属于自动变量。

二、断言(assert)assert关键字用于在程序运行时进行断言验证,如果断言条件为假,程序将会中止执行。

断言通常用于调试和排错。

三、带宽限定(band)band关键字用于限定带宽,常用于定义延迟函数、外部中断和总线访问等场景。

四、布尔类型(bool)bool关键字用于声明布尔类型的变量,布尔类型只有两个值:真和假。

一般用于判断语句和循环语句的条件。

五、跳过(break)break关键字用于跳出循环或者switch语句块,提前终止程序的执行。

六、函数调用(call)call关键字用于向函数传递参数并调用函数。

它与return关键字相对应,后者用于从函数返回结果。

七、case标签(case)case关键字用于定义switch语句中不同分支的标签,根据不同的条件执行相应的代码。

八、常量(const)const关键字用于声明常量,常量值在程序执行期间不可更改。

通常用于定义不变的特定值,提高代码的可读性和可维护性。

九、continue(continue)continue关键字用于结束当前循环的当前迭代,并进入下一轮循环的迭代。

通常用于跳过某些不满足条件的循环迭代。

十、默认(default)default关键字用于定义switch语句中默认分支的代码块。

如果没有匹配的case 标签,将会执行默认分支的代码。

十一、定义(define)define关键字用于定义宏。

宏是一种在程序编译之前被展开的符号常量或者代码片段。

c 中 explicit关键字的含义和用法

c  中 explicit关键字的含义和用法

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(constisbn_mismatch &e){ cerre.what()"left isbn is:"e.left"right isbn is:"e.rightendl;}}用于用户自定义类型的构造函数,指定它是默认的构造函数,不可用于转换构造函数。

C++关键字及说明解释

C++关键字及说明解释

C++关键词asmautobad_castbad_typeidboolbreakcasecatchcharclassconstconst_castcontinuedefaultdeletedodoubledynamic_cast elseenumexcept explicit externfalsefinallyfloatforfriendgotoifinlineintlongmutable namespaceoperator private protected publicregister reinterpret_cast returnshortsignedsizeofstaticstatic_caststructswitch templatethistruetrytype_infotypedeftypeid typename unionunsignedusingvirtualvoidvolatilewchar_t whileasm已经被__asm替代了,用于汇编语言嵌入在C/C++程序里编程,从而在某些方面优化代码.虽然用asm关键词编译时编译器不会报错,但是asm模块的代码是没有意义的.(2)auto这个这个关键词用于声明变量的生存期为自动,即将不在任何类、结构、枚举、联合和函数中定义的变量视为全局变量,而在函数中定义的变量视为局部变量。

这个关键词不怎么多写,因为所有的变量默认就是auto的。

(3)bad_cast,const_cast,dynamic_cast,reinterpret_cast,static_cast关于异常处理的,还不是太了解..(4)bad_typeid也是用于异常处理的,当typeid操作符的操作数typeid为Null指针时抛出.(5)bool不用多说了吧,声明布尔类型的变量或函数.(6)break跳出当前循环.The break statement terminates the execution of the nearest enclosing loop or conditional statement in which it appears.(7)caseswitch语句分支.Labels that appear after the case keyword cannot also appear outside a switch statement.(8)catch,throw,try都是异常处理的语句,The try, throw, and catch statements implement exception handling.(9)char声明字符型变量或函数.(10)class声明或定义类或者类的对象.The class keyword declares a class type or defines an object of a class type.(11)const被const修饰的东西都受到强制保护,可以预防意外的变动,能提高程序的健壮性。

C语言32以及C++63个关键字及其含义

C语言32以及C++63个关键字及其含义

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:大小,长度static:静态的struct:结构体switch:交换typedef:起别名union:共用体unsigned:无符号型void:无返回C++66个关键字的中文含义1.asm(汇编),用法如下:asm (指令字符串);允许在C++程序中嵌入汇编代码。

2. auto(自动,automatic)是存储类型标识符,表明变量“自动”具有本地范围,块范围的变量声明(如for循环体内的变量声明)默认为auto存储类型。

3. bool(布尔)类型,C++中的基本数据结构,其值可选为true(真)或者false(假)。

C++中的bool类型可以和int混用,具体来说就是0代表false,非0代表true。

bool类型常用于条件判断和函数返回值。

4. break(中断、跳出),用在switch语句或者循环语句中。

程序遇到break后,即跳过该程序段,继续后面的语句执行。

5. case用于switch语句中,用于判断不同的条件类型。

6. catch catch和try语句一起用于异常处理。

7. char char(字符,character)类型,C++中的基本数据结构,其值一般为0~255的int。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

这个 《ANSI/ISO C++ Professional Programmer's Handbook 》是这样说的 explicit Constructors A constructor that takes a single argument is, by default, an implicit conversion operator, which converts its argument to an object of its class (see also Chapter 3, "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 operator string(const char *); // constructor and implicit conversion operator ~string(); }; Class string has three constructors: a default constructor, a constructor that takes int, and a constructor that constructs a string from const char *. The second constructor is used to create an empty string object with an initial preallocated buffer at the specified size. However, in the case of class string, the automatic conversion is dubious. 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 object int ns = 0; s = 1; // 1 oops, programmer intended to write ns = 1, }
string(const char *); //implicit conversion ~string(); }; An explicit constructor does not behave as an implicit conversion operator, which enables the compiler to catch the typographical error this time: int main() { string s = "hello"; //OK, convert a C-string into a string object int 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 is useful 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 into string s; //pseudo C++ code: s = string ("Hello"); //create a temporary and assign it to s On the other hand, if you declare this constructor explicit, you have to use explicit type conversion:
Sales_item item1,item2,sum; while(cin>>item1>>item2) {
try{ sun=item1+item2; }catch(const isbn_mismatch &e) { cerr<<e.what()<<"left is:"<<e.right<<endl; } } 用于用户自定义类型的构造函数,指定它是默认的构造函数, 不可用于转换构造函 数.因为构造函数有三种: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(){} }; isbn is:"<<e.left<<"right isbn
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 first searches 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 written s = string(1); You might encounter a similar pro takes a string argument. The following example can either be a cryptic coding style or simply a programmer's typographical error. However, due to the implicit conversion 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 conversion
c++中 explicit 关键字的含义和用法 2009-02-27 14:56c++中的 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 );
相关文档
最新文档