我要定義一些通用指針(但不是一個空指針?):使用此代碼定義模板T作爲指針
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()
將無法編譯。 這兩個功能有什麼區別?
GCC說:
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
是什麼意思?
從option2中,
爲什麼只是刪除cv-qualifier會使這個編譯?
@ 0x499602D2我把錯誤信息放在我的文章中。 – mr5
選項2使它編譯,但不做你想要的。它返回一個const指針到一個非常量的ubyte,但是你不能指定一個新的指針到返回值,所以const是相對無用的:) – melak47
@ melak47謝謝,這是有道理的。 – mr5