【问题标题】:How to use a variable inside a _T wrapper?如何在 _T 包装器中使用变量?
【发布时间】:2011-05-29 18:08:09
【问题描述】:

我想让这个字符串的主机名部分成为可变的.. 目前,它只修复了这个 URL:

_T(" --url=http://www.myurl.com/ --out=c:\\current.png");

我想做这样的东西,所以网址是可变的..

_T(" --url=http://www." + myurl +  "/ --out=c:\\current.png");

更新。以下是我的最新尝试:

      CString one   = _T(" --url=http://www.");
      CString two(url->bstrVal);
      CString three = _T("/ --out=c:\\current.png");
      CString full = one + two + three;

      ShellExecute(0,                           
               _T("open"),        // Operation to perform
               _T("c:\\IECapt"),  // Application name
               _T(full),// Additional parameters
               0,                           // Default directory
               SW_HIDE);

错误是:Error 1 error C2065: 'Lfull' : undeclared identifier c:\test.cpp

【问题讨论】:

    标签: c++ visual-c++ mfc


    【解决方案1】:

    如果您在对 ShellExecute 的调用中从“full”左右丢失了 _T(),那么您的最新尝试将起作用。 CString 将返回正确的指针。任务完成。

    除此之外......你应该完全失去 _T() 的东西。如果您要直接执行诸如引用 url->bstrVal 之类的操作(这是 Unicode,无论您要编译什么),那么您的代码将只能作为 Unicode 工作。

    现在几乎没有理由为 Unicode 和 ANSI 编译同一个项目。创建 _T() 东西是为了“轻松”解决这两种模式。但除非您的目标是 Win95/98/ME,否则您可以使用 Unicode 并清理您的代码。 Unicode 也更快,因为 Windows API 和内核在内部是 Unicode。所有 ANSI API 首先将字符串参数转换为 Unicode,然后调用它们对应的宽字符。

    所以没有 _T、TCHAR 等。改用这样的东西:

    PWSTR psz = L"my unicode string";
    CString s = L"my other string, yay!";
    

    【讨论】:

      【解决方案2】:

      它不起作用,因为 _T() 宏仅适用于 constant 字符串文字。 _T() 的定义如下所示:

      #ifdef UNICODE
      #define _T(str) L##str
      #else
      #define _T(str) str
      

      由于您显然是在 Unicode 模式下编译,_T(full) 扩展为 Lfull,这显然不是您想要的。

      在您的情况下,只需传入不带_T() 宏的full,因为CString 在Unicode 模式下定义了到const wchar_t* 的转换运算符,在非Unicode 模式下定义了const char*

      ShellExecute(0, _T("open"), _T("c:\\IECapt"), full, 0, SW_HIDE);
      

      请注意,标准 C++ 还提供了 std::string 类型和 std::wstring 类型,这与 CString 所做的差不多,因此实际上不需要 MFC 来进行字符串操作。 std::string提供转换运算符,但提供通过c_str()访问底层C风格字符串。

      【讨论】:

        【解决方案3】:

        除了 In silico 所说的,CString::Format 让这段代码更具可读性:

        CString full;
        full.Format(_T(" --url=http://www.%s/ --out=c:\\current.png"), url->bstrVal));
        

        【讨论】:

          猜你喜欢
          • 2022-07-12
          • 2021-12-15
          • 2011-10-04
          • 2022-01-16
          • 2021-09-30
          • 2013-09-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多