从 CString 到 char*/TCHAR* 的转换
我很清楚将 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.
是的,绝对可以编写函数(最好是模板化函数)。但这涉及调用函数,并且作为赋值运算符并不顺利。
I am well aware of techniques to convert CString
to a C-style character. One of them is to use strcpy
/_tcscpy
, and others include using CStrBuf
.
The problem:
char Destination[100];
CStringA Source; // A is for simplicity and explicit ANSI specification.
Source = "This is source string."
Now I want this:
Destination = Source;
To happen automatically. Well, that logically means writing a conversion operator in CString
class. But, as implicit as it is, I dont have privileges to change the CString
class.
I thought of writing a global conversion opertor and global assignment operator. But it doesnt work:
operator char* (const CStringA&); // Error - At least must be class-type
operator = ... // Won't work either - cannot be global.
Yes, it is definitely possible to write function (preferably a templated one). But that involves calling the function, and it is not smooth as assignment operator.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能分配给数组。这使得你想要的事情变得不可能。另外,老实说,这是一件非常错误的事情 - 一个神奇数字大小的缓冲区?
You cannot assign to arrays. This makes what you want impossible. Also, honestly, it's a pretty wrong thing to do - a magic-number-sized buffer?
好吧,我不想说这在任何方面都是值得推荐的,但是您可以劫持一些较少使用的运算符来进行快速破解:
您甚至可以为静态大小的数组设置一个适度安全的模板化版本:
Well, I don't want to say that this is in any way recommendable, but you could hijack some lesser-used operator for a quick hack:
You could even rig up a moderately safe templated version for statically sized arrays:
CString
上的运算符无法解决问题,因为您需要复制到Destination
缓冲区,尽管此赋值会更改 Destination 的值,但这是不可能的。不知何故,您需要一个运算符来实现这一行:
正如您所看到的,转换 Source 仅完成了一半。您仍然需要复制到目标缓冲区。
另外,我不推荐它,因为
Destination = Source
行在char[]
语义方面完全具有误导性。唯一可能的此类分配是 Destination 的初始化:
An operator on
CString
won't solve the problem since you need to copy toDestination
buffer although this assignment would change the value of Destination, which is impossible.Somehow, you need an operator to achive this line:
As you can see, converting Source is only half way. You still need to copy to the destination buffer.
Also, I wouldn't recommend it because the line
Destination = Source
is completely misleading in regard of thechar[]
semantics.The only possible such assignment would be an initialisation of Destination: