如何将LPTSTR转换为LPCTSTR&

时间:2017-10-03 06:05:49

标签: c++

函数参数是LPCTSTR&

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

如何将LPTSTR转换为LPCTSTR&

提前致谢。

1 个答案:

答案 0 :(得分:3)

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

  1. 使参数为const,以便编译器可以接受LPSTR。
  2. 或者创建一个LPCTSTR指针(可以更改的左值)并传递它。
  3. 我必须尝试在以下代码段中解释它。我使用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;
    }
    
相关问题