[英]C++ “conversion loses qualifiers” compile error
我今天在調試 SWIG 類型映射時遇到了一個有趣的問題。 任何人ourLib::Char *
啟發我,為什么 Visual C++ 2008 在從ourLib::Char *
轉換為const ourLib::Char * &
時會拋出“轉換丟失限定符”錯誤? 我認為Type *
-> const Type *
是一個微不足道的轉換,並且(在調用函數時) Lvalue
-> Lvalue &
也是如此。
編輯:我們最終采用的解決方案:
// ourLib::Char is a typedef'ed char on Win32
%typemap(in) const char* (const ourLib::Char* tmp)
{
if (!bapiLua::LuaTraits<ourLib::Char*>::FromLuaObject(L, $argnum, tmp)) SWIG_fail;
$1 = const_cast<char *>(tmp);
}
// And in a different source file, already written:
namespace bapiLua {
template<>
struct LuaTraits<ourLib::Char*>
{
static ourLib::Bool FromLuaObject(lua_State* L, int pos, const ourLib::Char*& o_result);
};
}
從const ourLib::Char * tmp
刪除const
會導致我描述的錯誤。
假設你有以下功能:
void test( const char*& pRef)
{
static const char somedata[] = { 'a' ,'b', 'c', '\0'};
pRef = somedata;
}
如果您傳入一個非常量char*
,那么當test()
返回時,編譯器將失去p
指向的是const
的事實。
這基本上與這個 C++ FAQ Lite 問題中給出的原因相同(處理指針到指針而不是指針引用):
在以下代碼中,
friend ostream & operator<<(ostream & output, const List& other)
{
for(int i=0;i<other.length();i++)
output << other.getData()[i] << " ";
return output;
}
為了消除編譯錯誤“Conversion losss qualifiers”,對於參數“const List& other”,我將以下兩個調用方法都更改為const。
T* getData() const
{
return data;
}
int length() const
{
return lSize;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.