gpt4 book ai didi

c++ - 如何将 LPTSTR 转换为 LPCTSTR&

转载 作者:行者123 更新时间:2023-11-27 23:50:57 24 4
gpt4 key购买 nike

函数参数为LPCTSTR&

我必须将 LPTSTR 变量作为 LPCTSTR& 传递。

如何将LPTSTR转换为LPCTSTR&

提前致谢。

最佳答案

根据我以前的 C++ 经验,您正试图通过引用将指针传递给 const 字符串。编译器认为您要更改指针值。所以你有两个选择

  1. 将参数设置为 const,以便编译器可以接受 LPSTR。
  2. 或者创建一个 LPCTSTR 指针(一个可以改变的左值)并传递它。

我必须尝试在以下代码片段中对其进行解释。我用的是 VS 2017 + Windows 7 + SDK 10

void Foo(LPCTSTR &str)
{
std::wcout << str;
str = _T("World");
}

void FooConst(LPCTSTR const &str)
{
std::wcout << str;
//str = _T("World"); will give error
}

int main()
{
LPTSTR str = new TCHAR[10];
LPCTSTR str1 = str;
lstrcpy(str, _T("Hello"));

// Foo(str);// Error E0434 a reference of type "LPCTSTR &" (not const - qualified) cannot be initialized with a value of type "LPTSTR" HelloCpp2017
// Foo(static_cast<LPCTSTR>(str));// Error(active) E0461 initial value of reference to non - const must be an lvalue HelloCpp2017 d : \jfk\samples\cpp\HelloCpp2017\HelloCpp2017\HelloCpp2017.cpp 19

// Tell compiler you will not change the passed pointer
FooConst(str);

// Or provide a lvalue pointer that can be changed
Foo(str1);

std::wcout << str1;

return 0;
}

关于c++ - 如何将 LPTSTR 转换为 LPCTSTR&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46538109/

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