gpt4 book ai didi

Visual Studio 2012 : LPCWSTR and wstring 中的 C++ 编译错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:46:24 24 4
gpt4 key购买 nike

以下代码在 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;
}

返回的错误是:

error C2440: 'type cast' : cannot convert from 'CTestObj' to 'std::wstring'
No constructor could take the source type, or constructor overload resolution was ambiguous

我已经意识到,注释掉其中一个转换运算符可以解决编译问题。我只想了解:

  1. 背后发生了什么
  2. 为什么这会在 VS2010 而不是在 VS2012 中编译?是因为 C++11 的变化吗?

最佳答案

如果我理解引擎盖下的逻辑,运算符重载会在您每次转换时尝试复制代码和对象。因此,您需要 return it as a reference而不是尝试根据该字段返回一个新对象。线路:

operator std::wstring() const { return m_tmp; }

应该是:

operator std::wstring&() { return m_tmp; }

以下编译并按预期运行。

#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;
}

关于Visual Studio 2012 : LPCWSTR and wstring 中的 C++ 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10842878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com