(编辑:重大改变,因为前面的例子是有缺陷的,这可能会使一些答案/评论看起来很奇怪)
这可能是一个过于设计,但由于缺少const构造函数,以下是合法的:
class Cheater
{
public:
Cheater(int avalue)
: cheaterPtr(this) //conceptually odd legality in const Cheater ctor
, value(avalue)
{}
Cheater& getCheaterPtr() const {return *cheaterPtr;}
int value;
private:
Cheater * cheaterPtr;
};
int main()
{
const Cheater cheater(7); //Initialize the value to 7
cheater.value = 4; //good, illegal
cheater.getCheaterPtr().value = 4; //oops, legal
return 0;
}
Run Code Online (Sandbox Code Playgroud)
似乎提供const构造函数在技术上就像const方法一样容易,并且类似于const重载.
注意:我不是在寻找' Image( const Data & data ) const'而是' const Image( const Data & data) const'
所以:
这是上下文的一些相关材料:
我经常发现自己必须定义一个函数的两个版本,以便有一个是const的,一个是非const的(通常是一个getter,但并不总是).两者的不同之处仅在于一个的输入和输出是const,而另一个的输入和输出是非const.功能的胆量 - 真正的工作,是IDENTICAL.
然而,为了保持正确性,我需要它们.作为一个简单的实际示例,请采取以下措施:
inline const ITEMIDLIST * GetNextItem(const ITEMIDLIST * pidl)
{
return pidl ? reinterpret_cast<const ITEMIDLIST *>(reinterpret_cast<const BYTE *>(pidl) + pidl->mkid.cb) : NULL;
}
inline ITEMIDLIST * GetNextItem(ITEMIDLIST * pidl)
{
return pidl ? reinterpret_cast<ITEMIDLIST *>(reinterpret_cast<BYTE *>(pidl) + pidl->mkid.cb) : NULL;
}
Run Code Online (Sandbox Code Playgroud)
如你所见,他们做同样的事情.我可以选择用另一个使用更多的演员来定义一个,如果胆量 - 实际工作,则更为简单:
inline const ITEMIDLIST * GetNextItem(const ITEMIDLIST * pidl)
{
return pidl ? reinterpret_cast<const ITEMIDLIST *>(reinterpret_cast<const BYTE *>(pidl) + pidl->mkid.cb) : NULL;
}
inline ITEMIDLIST * GetNextItem(ITEMIDLIST * pidl)
{
return const_cast<ITEMIDLIST *>(GetNextItem(const_cast<const ITEMIDLIST …Run Code Online (Sandbox Code Playgroud)