从CString到char*/TCHAR*的转换

Conversion from CString to char*/TCHAR*

本文关键字:TCHAR 转换 char CString      更新时间:2023-10-16

我很清楚将CString转换为c风格字符的技术。其中一种是使用strcpy/_tcscpy,还有一种是使用CStrBuf

问题:

char Destination[100];
CStringA Source; // A is for simplicity and explicit ANSI specification.
Source = "This is source string."

现在我想要这个:

Destination = Source;

自动发生。嗯,这在逻辑上意味着在CString类中编写转换操作符。但是,正如隐含的那样,我没有特权来更改CString类。

我想写一个全局转换操作符和全局赋值操作符。但是它不起作用:

operator char* (const CStringA&); // Error - At least must be class-type
operator = ... // Won't work either - cannot be global.

是的,写函数是绝对可能的(最好是模板化的)。但是这涉及到调用函数,并且它不像赋值操作符那样流畅。

不能给数组赋值。这让你想要的变得不可能。而且,老实说,这是一件非常错误的事情——一个神奇数字大小的缓冲区?

好吧,我不想说这在任何方面都是值得推荐的,但是您可以劫持一些较少使用的操作符来快速破解:

void operator<<=(char * dst, const std::string & s)
{
  std::strcpy(dst, s.c_str());
}
int main()
{
  char buf[100];
  std::string s = "Hello";
  buf <<= s;
}

您甚至可以为静态大小的数组设置一个中等安全的模板版本:

template <typename TChar, unsigned int N>
inline void operator<<=(TChar (&dst)[N], const std::string & s)
{
  std::strncpy(dst, s.c_str(), N);
}

CString上的操作符不能解决这个问题,因为你需要复制到Destination缓冲区,尽管这个赋值会改变Destination的值,这是不可能的。

无论如何,您需要一个操作符来实现这一行:

strcpy(Destination, LPCSTR(Source)); // + buffer overflow protection

如您所见,转换Source只是完成了一半。您仍然需要复制到目标缓冲区。

同样,我也不推荐这样做,因为Destination = Source行完全误导了char[]的语义。

唯一可能的赋值是初始化Destination:

char Destination[100] = Source;