1. 程式人生 > >C++ explicit關鍵字

C++ explicit關鍵字

首先, C++中的explicit關鍵字只能用於修飾只有一個引數類建構函式, 它的作用是表明該建構函式是顯示的, 而非隱式的, 跟它相對應的另一個關鍵字是implicit, 意思是隱藏的,類建構函式預設情況下即宣告為implicit(隱式).

#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

class A
{
    public:
        int _size;

        /*
         * 報錯 error: invalid conversion from ‘int’ to ‘const char*’
         * */
        explicit A(int size)
        /*
         * 沒有錯誤
         * */
        //A(int size) 
        {
            _size = size;
        }
        A(const char *p)
        {
            _size = strlen(p);
        }
};

int main()
{
    A str1(24);
    A str2 = 10;
    A str4("aaaa");
    A str5 = "bbb";
    A str6 = 'c';
    str1 = 2;
    str2 = 3;

    return 0;
}

上面的程式碼中, "A str2 = 10;" 這句為什麼是可以的呢? 在C++中, 如果的建構函式只有一個引數時, 那麼在編譯的時候就會有一個預設的轉換操作:將該建構函式對應資料型別的資料轉換為該類物件. 也就是說 "A str2 = 10;" 這段程式碼, 編譯器自動將整型轉換為A類物件, 實際上等同於下面的操作:

A str2(10);  
或  
A temp(10);  
A str2 = temp;