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

狮王

我写了一个像下面这样的 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 wchar_t(*const cString);我认为,与之匹配的 typedef 是(通常不会const像这样typedef 一个指针,所以我不是 100% 确定语法)

但是,wstring::c_str()返回一个指向const数据的可变指针与此匹配的 typedef 将是typedef (const wchar_t) *cString;,带或不带括号。

因此func(wstring::c_str()),将指向常量数据的(可变)指针传递给需要指向可变数据的(常量)指针的函数。指针本身可以从 mutable 转换为const,但是它指向的数据不能默默地从constmutable转换为 mutable,所以它告诉你有问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章