jqc*_*gel 6 c++ visual-studio-2010 wstring visual-c++ visual-studio-2012
以下代码在Visual Studio 2010中编译,但无法在Visual Studio 2012 RC中编译.
#include <string>
// Windows stuffs
typedef __nullterminated const wchar_t *LPCWSTR;
class CTestObj {
public:
CTestObj() {m_tmp = L"default";};
operator LPCWSTR() { return m_tmp.c_str(); } // returns const wchar_t*
operator std::wstring() const { return m_tmp; } // returns std::wstring
protected:
std::wstring m_tmp;
};
int _tmain(int argc, _TCHAR* argv[])
{
CTestObj x;
std::wstring strval = (std::wstring) x;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
返回的错误是:
错误C2440:'type cast':无法转换
'CTestObj'为'std::wstring'
No构造函数可以采用源类型,或构造函数重载解析不明确
我已经意识到,注释掉任何转换运算符都会修复编译问题.我只想了解:
如果我理解底层的逻辑,那么运算符重载会在每次强制转换时尝试复制代码和对象。因此,您需要将其作为引用返回,而不是尝试基于该字段返回新对象。该行:
operator std::wstring() const { return m_tmp; }
Run Code Online (Sandbox Code Playgroud)
应该:
operator std::wstring&() { return m_tmp; }
Run Code Online (Sandbox Code Playgroud)
以下内容按预期编译并运行。
#include <string>
// Windows stuffs
typedef __nullterminated const wchar_t *LPCWSTR;
class CTestObj {
public:
CTestObj() {m_tmp = L"default";};
operator LPCWSTR() { return m_tmp.c_str(); } // returns const wchar_t*
operator std::wstring&() { return m_tmp; } // returns std::wstring
protected:
std::wstring m_tmp;
};
int main()
{
CTestObj x;
std::wstring strval = (std::wstring) x;
wprintf(L"%s\n", strval.c_str());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1608 次 |
| 最近记录: |