C++ 如何将LPTSTR转换为LPCTSTR&;
函数参数为C++ 如何将LPTSTR转换为LPCTSTR&;,c++,C++,函数参数为LPCTSTR& 我必须将LPTSTR变量作为LPCTSTR&传递 如何将LPTSTR转换为LPCTSTR& 提前感谢。 < P>从我以前的C++经验中,你试图通过引用传递一个指向const字符串的指针。编译器认为您将要更改指针值。所以你有两个选择 使参数为常量,以便编译器可以接受LPSTR 或者创建一个LPCTSTR指针(可以更改的左值)并传递它 我不得不在下面的代码片段中解释它。我使用了VS2017+Windows 7+SDK 10 void Foo(LPCTSTR &st
LPCTSTR&
我必须将LPTSTR
变量作为LPCTSTR&
传递
如何将LPTSTR
转换为LPCTSTR&
提前感谢。
< P>从我以前的C++经验中,你试图通过引用传递一个指向const字符串的指针。编译器认为您将要更改指针值。所以你有两个选择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;
}
void Foo(LPCTSTR&str)
{
STD::WcOut从我的旧C++经验中,你试图通过引用传递一个指向const字符串的指针。编译器认为你将改变指针值。因此你有2个选项
使参数为常量,以便编译器可以接受LPSTR
或者创建一个LPCTSTR指针(可以更改的左值)并传递它
我试图在下面的代码片段中解释它。我使用了VS2017+Windows7+SDK10
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;
}
void Foo(LPCTSTR&str)
{
std::wcout LPTSTR data=\u T(“Hello”);LPCTSTR const\u data=static\u cast(data);您正在调用什么函数?@AseshLPTSTR
不必是unicode,您应该使用\u T
宏您有什么问题?函数接受(引用)const指针应该没有问题接受指针…LPTSTR data=\u T(“Hello”);LPCTSTR const_data=static_cast(data);您正在调用什么函数?@AseshLPTSTR
不必是unicode,您应该使用\u T
宏您有什么问题?函数接受(参考)常量指针在接受指针时应该没有问题…@Asesh我编写代码只是为了显示与此问题相关的问题和解决方案。它不完整。@Asesh我编写代码只是为了显示与此问题相关的问题和解决方案。它不完整。