在 typedef 内部使用 const 关键字和在 typedef 外部使用 const 关键字之间有区别吗?

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

本文关键字:const 关键字 typedef 有区别 外部 内部 之间      更新时间:2023-10-16

我写了一个像下面这样的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",尽管类型cString是用独立constwchar_t *的。

为了解决这个问题,我必须将 typedef 定义为typedef const wchar_t *cString;或直接使用const wchar_t*而不使用 typedef。

为什么会出现这个问题?

typedef wchar_t *cString;cString声明为指向可变数据的可变指针。

const cString声明了其中之一const,因此它是指向可变数据的const指针。 我认为,与此匹配的类型定义将是typedef wchar_t(*const cString);。(通常不会像这样键入const指针,所以我对语法不是 100% 确定(

但是,wstring::c_str()返回指向const数据的可变指针。匹配的类型定义是typedef (const wchar_t) *cString;,带或不带括号。

因此,func(wstring::c_str())传递一个指向 const 数据的(可变(指针,传递到一个期望指向可变数据的 (const( 指针的函数。 指针本身可以从可变转换为const,但它指向的数据不能静默地从const转换为可变,所以它告诉你有问题。

您的参数属于const wchar_t *类型(又名wchar_t const *(。

您的参数类型为wchar_t * const("独立const"排在最后(。

有区别。