C 關鍵字explicit的用法

2021-08-28 06:03:26 字數 1545 閱讀 4112

c++關鍵字explicit,可以阻止不應該允許的經過轉換建構函式進行的隱式轉換的發生,宣告為explicit的建構函式不能在隱式轉換中使用。

c++中, 帶有乙個形參的建構函式(或者除了第乙個引數外其餘引數都有預設值的多參建構函式), 承擔了兩個角色。 

1 是類的帶參建構函式;2 是預設且隱含的型別轉換操作符。

比如乙個類class a, 有時候在我們寫下如 a a= ***, 這樣的**, 且恰好***的型別正好是類a的單引數構造器的引數型別, 這時候編譯器就自動呼叫這個構造器, 建立乙個a的物件。

請看下面**:

person.h:

#pragma once

#include "stdafx.h"

#include

class cperson

;person.cpp:

#include "stdafx.h"

#include "cperson.h"

cperson::cperson()

cperson::~cperson()

cperson::cperson(string strname)

string cperson::getname()

void cperson::setname(string strname)

string cperson::get***()

void cperson::set***(string str***)

int cperson::getage()

void cperson::setage(int nage)

void cperson::showperson()

main.cpp:

// keywordtest.cpp: 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include "cperson.h"

int main()

{cperson person("zzzzzzzzzzzzzzzzzz");

cout << "person age:"<

cout << endl;

cperson person2 = string("wwwwwwwwwwwwwwwwww");

cout << "person2--------------:" << endl;

person2.showperson();

return 0;

用2處**,沒用explicit修飾單個引數的建構函式,**沒問題!

用1處**,用explicit修飾單引數的建構函式,**不能通過編譯!

特別注意

explicit只能寫在宣告中,不能寫在定義中。

C 關鍵字explicit的用法

explicit是顯示的意思。而且只能修飾建構函式。因為在類的建構函式中,凡是只帶乙個引數的建構函式,都定義了一組隱式轉化 把建構函式型別轉換為該類的型別。比如 class explicit virtual explicit 則 呼叫 explicit e 1 列印 explicit 建構函式 1 ...

C 關鍵字explicit的用法

下面c 程式的輸出 include using namespace std class complex a method to compare two complex numbers bool operator complex rhs int main 輸出 編譯通過,產生輸出。same 在c 中,...

explicit 關鍵字的用法

explicit 關鍵字的用法 只有乙個引數的建構函式在預設情況下隱含乙個轉換操作符,對沒有引數或引數個數大於 1 個的建構函式沒有此問題 看後面的特別說明 class x int m a int m b double m c x x int a 如果做如下呼叫 x x 10 10 被隱式轉化成了 ...