我有一些問題,使用const_cast刪除常量。錯誤味精說「轉換爲有效的標準轉換......」C++。爲什麼我無法編譯此代碼?使用const_cast去除常量有什麼問題?
是什麼這個問題的本質是什麼?爲什麼我應該使用C風格演員? 「
」錯誤C2440:'const_cast':無法從'const size_t'轉換爲'size_t'「 」轉換是一種有效的標準轉換,可以隱式執行或使用static_cast,C風格轉換或函數式的鑄造」
template<typename T>
const IFixedMemory* FixedMemoryPkt<T>::operator=(const IFixedMemory* srcObj)
{
// doesn't remove constness this way. why?
const_cast<char*> (this->m_Address) = (char*)srcObj->GetAddress();
// compile this way, but maybe(?) undefined behaviour
// const_cast<char*&> (this->m_Address) = (char*)srcObj->GetAddress();
// doesn't doesn't work too
const_cast<size_t> (this->m_Size) = (size_t)(srcObj->GetSize());
// const_cast<size_t> (this->m_Size) = 0;
return this;
}
template<typename T>
class FixedMemoryPkt : public IFixedMemory
{
private:
const size_t m_Size;
const char* m_Address;
}
class IFixedMemory
{
public:
virtual const char* GetAddress() const = 0;
virtual size_t GetSize() const = 0;
}
所以你的*固定的內存包*也不是那麼固定畢竟?從名字來看,這個類似乎不應該是可複製/賦值的。 – Praetorian
你的對象沒有'm_Memory'成員。請發佈真實的代碼,而不是假的。 – AnT
或者無論如何,請在發佈前爲自己編譯僞代碼,以確認它顯示的是與真實代碼相同的問題。 –