我写了一个像下面这样的 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
是wchar_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
,但是它指向的数据不能默默地从const
mutable转换为 mutable,所以它告诉你有问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句