如何在 _T 包装器中使用变量?

2021-12-22 00:00:00 visual-c++ c++ mfc

我想让这个字符串的主机名部分是可变的..目前,它只修复了这个 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 二(url->bstrVal);CString 三 = _T("/--out=c:\current.png");CString full = 一+二+三;外壳执行(0,_T("open"),//要执行的操作_T("c:\IECapt"),//应用名称_T(full),//附加参数0,//默认目录SW_HIDE);

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

解决方案

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

#ifdef UNICODE#define _T(str) L##str#别的#define _T(str) str

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

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

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

<小时>

请注意,标准 C++ 还提供了一个 std::string 类型和一个 std::wstring 类型,它们的作用与 CString 的作用差不多,因此字符串操作实际上不需要 MFC.std::string 确实不提供转换运算符,但确实通过c_str() 提供对底层 C 样式字符串的访问.

I want to make the hostname part of this string to be variable.. Currently, it is only fix to this URL:

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

I want to make something like this, so the URL is changeable..

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

update. Below is my latest attempt:

      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);

The error is : Error 1 error C2065: 'Lfull' : undeclared identifier c: est.cpp

解决方案

It doesn't work because the _T() macro works only with constant string literals. The definition for _T() looks something like this:

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

Since you're apparently compiling in Unicode mode, _T(full) expands to Lfull, which is obviously not what you want.

In your case, just pass in full without the _T() macro since CString defines a conversion operator to a const wchar_t* in Unicode mode, and const char* in non-Unicode mode.

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


Note that standard C++ also provides a std::string type and a std::wstring type which does pretty much what CString does, so MFC isn't actually required for string manipulation. std::string does not provide a conversion operator, but does provide access to the underlying C-style string via c_str().

相关文章