2017-10-03 10 views
0

関数のパラメータはLPCTSTR&です。LPTSTRをLPCTSTRに変換する方法&

LPTSTRという変数をLPCTSTR&として渡す必要があります。

LPTSTRLPCTSTR&に変換する方法

ありがとうございます。

+0

LPTSTR data = _T( "Hello"); \t LPCTSTR const_data = static_cast (データ); – Asesh

+0

あなたはどのような機能を呼びますか? –

+3

@Asesh 'LPTSTR'はユニコードである必要はありません。' _T'マクロを使うべきです – vasek

答えて

3

私の古いC++の経験から、参照によってconst文字列へのポインタを渡そうとしています。コンパイラは、ポインタ値を変更しようとしていると考えます。したがって、2つのオプションがあります。

  1. コンパイラがLPSTRを受け入れるようにパラメータをconstにします。
  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; 
} 
+0

コードにメモリリークがあります。 – Asesh

+0

@Aseshこの問題に関して、問題と解決策を示すためにコードを書いています。それは完全ではありません。 – ferosekhanj

関連する問題