将模板化 T 定义为指针
Define a templated T as pointer
我想使用以下代码定义一些通用指针(?但不是空指针):
class A
{
template<typename T>
using ptr = T*;
using ubyte = uint8_t;
public:
const ptr<ubyte>
getColor1() const {
return &colors[0];
}
const ubyte*
getColor2() const {
return &colors[0];
}
private:
ubyte colors[4];
};
但是,getColor1()
不会编译。这两个函数有什么区别?
海湾合作委员会 说:
error: invalid conversion from 'const ubyte* {aka const unsigned char*}' to 'A::ptr<unsigned char> {aka unsigned char*}' [-fpermissive]|
更新:
删除的答案说我可以这样做:
//option 1
template<typename T>
using const_ptr = const T*;
或
//option 2
const ptr<ubyte>
getColor() //remove cv-qualifier
{
return &colors[0];
}
从选项 1,
它现在构造为const const
,const const
是什么意思?
从选项 2,
为什么只删除 cv 限定符就可以编译?
const ptr<ubyte>
与const (ubyte *)
相同,这与const ubyte (*)
不同。您正在尝试返回指向非常量char
的const
指针,编译器不允许这样做,因为您已将函数本身声明为const
;因此,所有成员都成为const
。编译器不会在没有const_cast
的情况下自动将 const 转换为非 const 。
为了使区别更清楚,第一个是指向非常量char
的常量指针,第二个是指向常量char
的非常量指针。第一个允许指向的字符更改,即使指针本身无法更改。由于该函数被标记为const
因此它无法返回任何允许修改其成员的内容。
修复它的最佳方法:
ptr<const ubyte>
getColor1() const {
return &colors[0];
}
由于ptr
模板的语法,const ptr<ubyte>
首先使其成为ubyte*
,然后应用常量,从而产生一个ubyte * const
,一个指向 ubyte 的常量指针。
为了返回指向 const ubyte 的指针,您需要将const ubyte
馈送到指针模板中,因此首先应用常量:
ptr<const ubyte>
1)"const const 是什么意思?
const T* const pT = new T;
表示常量指针 pT - 您不能将 pT 分配给另一个对象;到 T 类型的 const 对象 - 您无法更改 pT 指向的对象。
2)"为什么只是删除cv限定符就可以编译这个?
getColor1()
没有 const 修饰符的方法可以修改对象。它现在返回 A::ubyte*,可以转换为 const 类型,例如声明为返回类型:A::ubyte* const (const ptr
- 用户定义函数中的指针和输入
- 使用"Task"函数指针队列定义作业管理器
- 通过函数指针定义类范围之外的方法
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 如何重新定义 C++ 指针函数?
- 返回对未定义指针的引用
- 为什么此自定义指针类会崩溃?
- 如何定义指针铸件操作员
- 定义指针随机崩溃该程序
- 在不同的文件(C++)中定义指针数组长度
- 如何定义指针和动态内存分配的模板
- 具有自定义指针类型的unique_ptr:*get() 和运算符*() 给出不同的输出
- 定义指针时不显示输出;
- 自定义指针类型和容器/分配器类型定义
- 并排定义指针和类型问题
- 具有自定义指针类型的内存分配器
- 正在对unordered_set的自定义指针类型进行哈希处理
- 查找全局定义指针指向的地址,该地址使用了堆分配
- 如何有效地计算已定义指针的数量
- 用户定义指针队列中的分段错误