You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用类型别名时const pointer与const_pointer的转换错误问题

关于const pointer与const_pointer的类型区别解析

你的问题核心是没搞清楚类型别名前加const和直接定义带const的类型别名的本质区别:

1. 两种类型的真实含义

  • const_pointer是你直接定义的类型别名,等价于const int*,也就是指向const int的指针:指针本身可以被修改,但它指向的内存内容不能被修改。
  • const pointer里的const是修饰pointer这个类型的,而pointer本身是int*,所以const pointer等价于int* const,也就是指向int的常量指针:指针本身不能被修改,但它指向的内存内容可以被修改。

2. 编译错误的原因

在const成员函数get()中,this指针的类型是const S*,因此成员变量i的类型会被视为const int,取地址后&i的类型是const int*。

  • 当返回const_pointer时,const int*和const_pointer类型完全匹配,编译正常。
  • 当返回const pointer时,你试图把const int*转换为int* const:int* const允许修改指向的内容,但const int*指向的内容是只读的,这种转换会破坏const安全性,因此编译器直接报错。

3. 修正方案

  • 如果你的需求是返回一个指向只读int的指针,直接使用const_pointer作为返回类型即可(就是你注释掉的那行代码)。
  • 如果确实需要返回int* const,只能在非const成员函数中实现,此时i的类型是普通int,&i是int*,可以隐式转换为int* const。

内容的提问来源于stack exchange,提问作者user1166

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 15:52:07