C++文法之explicit

來源:互聯網
上載者:User
1 -- 隱式類型轉換帶來的問題

我們首先看下面的這個例子,它可編譯也可執行,最終結果是“TDemo::print 55”。有理由推斷,執行個體化一個對象時,編譯器自動將55這個整數轉換成了“class TDemo”。類TDemo定義了一個單參數建構函式,而C++標準中,“單參數建構函式,可以完成從形參到該類型的一個隱式轉換”,所以編譯器能夠完成從int類型到TDemo的類型轉換。

#include <iostream>class TDemo{public:TDemo(int num);void print() const { std::cout 2 -- 禁止隱式類型轉換調用“TDemo demo = 55”實際就是“TDemo demo = TDemo(55)”,編譯器隱式調用單參數建構函式產生一個TDemo臨時對象,然後將該臨時對象複製給demo變數。有時候並不希望編譯器隱瞞我們,“私自”完成進行這種隱式轉換,在需要轉換的時候需要程式員明確使用顯示轉換,這樣寫下來的程式簡單清晰,還可以規避很多由隱式轉換引發的歧義和錯誤。這時就可以使用關鍵字explicit來禁止在需要隱式轉換的上下文中使用單參數建構函式。

修改上面例子程式,單參數建構函式使用explicit來修飾,再次編譯器後,發現會提示錯誤:“error: conversion from `int' to non-scalar type `TDemo' requested”,也就禁止了隱式類型轉換。
#include <iostream>class TDemo{public:explicit TDemo(int num);void print() const { std::cout 3 -- 使用explicit關鍵字注意事項explicit關鍵字只能用於類內部的建構函式聲明上,在類的定義體外部所做的定義上不在重複它。也就是下面兩種方式都是錯誤的:
class TDemo{public:TDemo(int num);};//error: only declarations of constructors can be `explicit'explicit TDemo::TDemo(int num):i_num(num){}
class TDemo{public:explicit TDemo(int num);};//error: only declarations of constructors can be `explicit'explicit TDemo::TDemo(int num):i_num(num){}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.