2011-08-24 94 views
2

我非常了解将CString转换为C风格字符的技巧。其中之一是使用strcpy/_tcscpy,其他包括使用CStrBuf从CString转换为char */TCHAR *

问题:

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. 

是的,这是绝对有可能写的函数(最好是一个模板)。但是这涉及到的调用的功能,并且它不是流畅的赋值运算符。

+0

我不知道,但你为什么不能定义一个全局'void运算符=(字符*&LHS,常量的CString&右)'?其中一个参数不是内置类型,所以重载应该是可能的。 –

+1

@Kerrek:赋值必须作为非静态成员函数重载。 –

+0

你不能在CString中使用GetBuffer(..)吗? – Simon

回答

1

好了,我不想说这是在任何方面推荐的,但是你可以劫持一些不经常使用的运营商进行快速黑客:

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); 
} 
+0

这太棒了。虽然不是完美的解决方案(这是不可能的),但非常感谢! – Ajay

0

CString上的运算符不会解决问题,因为您需要复制到Destination缓冲区,尽管此分配会更改Destination的值,这是不可能的。

不知何故,你需要一个运营商实现这一目标行:

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

正如你所看到的,把源只有一半。您仍然需要复制到目标缓冲区。

此外,我不会推荐它,因为Destination = Source行对于char[]语义完全是误导。

唯一可能的这样一个任务将是目的地的初始化:

char Destination[100] = Source; 
+0

如果我可以在'CString'类中编写运算符,我就可以。并且完全可以复制到char/TCHAR数组 - 只需使用模板方法或传递其他大小参数即可。 – Ajay

2

您不能分配到阵列。这使得你想要的不可能。另外,说实话,这是一个非常错误的事情 - 一个魔术数字大小的缓冲区?

+0

不是魔法大小的缓冲区 - 模板魔法解决了它。 – Ajay

+0

其实你有权 - 即使在课堂上,我们也不能返回数组。 – Ajay