在 typedef 内部使用 const 关键字和在 typedef 外部使用 const 关键字之间有区别吗?
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"
,尽管类型cString
是用独立const
wchar_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
"排在最后(。
有区别。
- 在 typedef 内部使用 const 关键字和在 typedef 外部使用 const 关键字之间有区别吗?
- 关于重载 -> 运算符中 const 关键字的特定位置的问题
- 为什么带有 const 关键字的构造函数可以工作,而没有它就不能工作?
- 为什么在函数参数编译中没有标识符的const关键字
- 为什么在代码块中重新计算 const 关键字
- 如果我返回const定义的对象,为什么const关键字被取消资格
- 带有函数签名的 Const 关键字
- 使用 "const" 关键字突出显示 C++ 的 Emacs 语法
- 模板转换运算符,需要'const'关键字
- C++函数中的 const 关键字
- 复制 ctor 和复制赋值运算符 const 关键字位置
- const关键字的默认数据类型为int类型
- 传递“const_iterator”作为参数时,我是否需要编写“const”关键字
- 为什么const关键字对于定义模板参数是必需的
- 使用const关键字重载签名相同的方法
- 模板参数中的Const关键字
- const关键字在操作符定义中做什么?
- 函数声明返回类型中的Const关键字
- 函数中的 Const 关键字带有 *&参数。
- const关键字的必要性是什么