MFC:std :: string与CString? [英] MFC: std::string vs CString?

查看:105
本文介绍了MFC:std :: string与CString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MFC中使用C ++.来自C#背景,我通常只将字符串用于所有字符串.我将它们用于类成员,方法参数和方法返回值.

Using C++ with MFC. Coming from a C# background I typically just use string for all, well, strings. I use them for class members, method parameters, and method return values.

现在在C ++中,我有std :: string,CString,char *,LPCTSTR等.在设计数据成员,方法参数和方法返回值时,应使用哪种类型?易用性很重要,CString似乎提供了这一点,但是我的直觉是对可移植标准的,尽管可移植性在我的优先级列表中(现在)还很低.另外,我不喜欢创建字符串缓冲区并将其传递给方法和函数的c语义.

Now in C++ I've got std::string, CString, char *, LPCTSTR, and more. As I design my data members, method parameters, and method return values which type(s) should I be using? Ease of use is important and CString seems to offer that but my instinct is toward portable standards although portability is pretty low on my list of priorities (now). Also, I don't like the c semantics of creating string buffers and passing them into methods and functions.

我认为从直接简化编码的角度来看,CString可能具有优势.但是,总的来说,执行此操作的高代码质量"方法是什么?

I think from an immediate ease of coding perspective CStrings probably have the edge. But, overall, what is the "high code quality" way to do this?

我特别担心代码中的接口点(即方法参数和返回值).例如:

I'm especially concerned about the interface points in my code (i.e. method parameters and return values). E.g.:

Shape::SetCaption(const char *caption) {...}

Shape::SetCaption(CString caption) {...}

Shape::SetCaption(std::string caption) {...}

Shape::SetCaption(std::wstring caption) {...}

推荐答案

我通常更喜欢使编码风格适应正在使用的框架,以使其与之保持一致.因此,当我使用MFC(已经很长时间了)时,我更喜欢使用CString(和LPCTSTR作为公共接口方法中的函数参数).当使用Qt时,我更喜欢QString和Qt的容器而不是STL容器,对于与该框架没有直接关系的所有内容,我都使用std::string,因为它是处理字符串的标准C ++方法.

I usually prefer to adapt my coding style to the framework I'm working in to be consistent with it. So when I work with MFC (which i haven't for a long time), I prefer the use of CString (and LPCTSTR as function arguments in public interface methods). When working with Qt I prefer QString and Qt's containers over STL containers and for everything not directly related to such a framework I use std::string as it's the standard C++ way of handling strings.

这并没有太大的区别,因为它们都提供或多或少的相等功能(并且可以很容易地相互转换),并且当为某个框架编写代码时,它仍然依赖于它,因此可移植性是没有那么大的担忧.

It doesn't make such a huge difference, since they all offer more or less equal functionality (and are easily convertible into each other) and when code is written for a certain framework, it depends on it anyway, so portability is not such a huge concern.

请不要理会纯字符数组!顺便说一句,尝试通过const引用(const std::string &caption)而不是按值传递对象,因为在C ++中,变量不会自动引用,并且复制字符串会变得非常昂贵.

Just don't bother with plain char arrays! And by the way, try to pass objects by const reference (const std::string &caption) and not by value, as in C++ variables are not automatically references and copying a string can get quite expensive.

这篇关于MFC:std :: string与CString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆