簡體   English   中英

在 typedef 內使用 const 關鍵字和在 typedef 外使用有區別嗎?

[英]Is there a difference between use const keyword inside typedef and outside typedef?

我寫了一個 typedef,如下所示:

typedef wchar_t *cString;

我將 const 關鍵字獨立放置如下:

void func(const cString)

但是當將wstring::c_str()傳遞給前一個方法func(wstring::c_str())時,它告訴我有一個argument of type "const wchar_t *" is incompatible with parameter of type "cString" ,盡管類型cStringwchar_t *具有獨立的const

為了解決這個問題,我必須將 typedef 定義為typedef const wchar_t *cString; 或者直接使用const wchar_t*而不使用 typedef。

為什么會出現這個問題?

typedef wchar_t *cString; cString聲明為指向可變數據的可變指針。

const cString聲明一個const其中之一,因此它是一個指向可變數據的const指針。 與之匹配的 typedef 將是typedef wchar_t(*const cString); , 我認為。 (通常不會像這樣 typedef 一個const指針,所以我不能 100% 確定語法)

但是, wstring::c_str()返回一個指向const數據的可變指針。 與之匹配的 typedef 將是typedef (const wchar_t) *cString; , 帶或不帶括號。

因此func(wstring::c_str())將一個(可變)指針傳遞給 const 數據,傳遞給一個 function ,它需要一個(const)指向可變數據的指針。 指針本身可以從 mutable 轉換為const ,但它指向的數據不能從const靜默轉換為 mutable ,因此它會告訴您有問題。

您的論點是const wchar_t * (又名wchar_t const * )類型。

您的參數是wchar_t * const類型(“獨立const ”排在最后)。

有區別

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM