【发布时间】:2011-11-02 17:37:09
【问题描述】:
我非常了解将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 * & lhs, const CString & rhs)?其中一个参数不是内置类型,因此重载应该是可能的。 -
@Kerrek:赋值必须作为非静态成员函数重载。
-
你不能使用 CString 中的 GetBuffer(..) 吗?
-
将
CString分配给固定大小的缓冲区有什么用? -
@R.玛特:哦,当然。嗯。也许您可以滥用其他一些您可以全局重载的很少使用的运算符?
标签: c++ visual-c++ mfc atl cstring