C++11 explicit关键字的作用
生活随笔
收集整理的這篇文章主要介紹了
C++11 explicit关键字的作用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
explicit
- 在C++中,explicit關鍵字用來修飾類的構造函數,被修飾的構造函數的類,不能發生相應的隱式類型轉換,只能以顯示的方式進行類型轉換。因為無參構造函數和多參構造函數本身就是顯示調用的。再加上explicit關鍵字也沒有什么意義。
explicit使用注意事項:
- explicit 關鍵字只能用于類內部的構造函數聲明上
- explicit 關鍵字作用于單個參數的構造函數。
- 在C++中,explicit關鍵字用來修飾類的構造函數,被修飾的構造函數的類,不能發生相應的隱式類型轉換
- 禁止類對象之間的隱式轉換
不使用explicit
#include <cstring> #include <string> #include <iostream> using namespace std; class Explicit{private:public:Explicit(int size){cout << "The size is " << size << endl;}Explicit(const char* str){string _str = str;cout << "The str is " << _str << endl;}Explicit(const Explicit& ins){cout << "The Explicit is ins " << endl;}Explicit(int a,int b){cout << "The a is " << a << ",the b is "<< b << endl;} };int main(){Explicit test0(15);Explicit test1 = 15;//隱式調用Explicit(int size)Explicit test2("QWERASDF");Explicit test3 = "QWERASDF";//隱式調用Explicit(const char* str)Explicit test4(1,10);Explicit test5 = test1; }- test0和test1是相同類型的,前者是顯示調用,后者是隱式調用。
- 同理,test2和test3也是一致的
- test4是調用加法運算,test5調用的函數要是Explicit就返回?The Explicit is ins.
-
上面的程序雖然沒有錯誤,但是對于Explicit test1 = 10;和Explicit test2 = "BUGBUGBUG";這樣的句子,把一個int類型或者const char*類型的變量賦值給Explicit類型的變量看起來總歸不是很好,并且當程序很大的時候出錯之后也不容易排查。所以為了禁止上面那種隱式轉換可能帶來的風險,一般都把類的單參構造函數聲明的顯示調用的,就是在構造函數加關鍵字``explicit`。如下:
- 上面再寫Explicit test1=10; Explicit test3 = "BUGBUGBUG";這樣的句子的時候程序就會報如下錯誤:
error: conversion from ‘int’ to non-scalar type ‘Explicit’ requested
error: conversion from ‘const char [10]’ to non-scalar type ‘Explicit’ requested
參考鏈接
- https://www.jianshu.com/p/af8034ec0e7a
?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的C++11 explicit关键字的作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 区块链相关问题 理解
- 下一篇: 2019民生车车信用卡加油金返还最新细则