Condividi tramite


CString Argument Passing

This article explains how to pass CString objects to functions and how to return CString objects from functions.

CString Argument-Passing Conventions

When you define a class interface, you must determine the argument-passing convention for your member functions. There are some standard rules for passing and returning CString objects. If you follow the rules described in Strings as Function Inputs and Strings as Function Outputs, you will have efficient, correct code.

Strings as Function Inputs

If a string is an input to a function, in most cases it is best to declare the string function parameter as LPCTSTR. Convert to a CString object as necessary within the function using constructors and assignment operators. If the string contents are to be changed by a function, declare the parameter as a nonconstant CString reference (CString&).

Strings as Function Outputs

Normally you can return CString objects from functions because CString objects follow value semantics like primitive types. To return a read-only string, use a constant CString reference (const CString&). The following example illustrates the use of CString parameters and return types:

class CName : public CObject
{
private:
   CString m_firstName;
   TCHAR m_middleInit;
   CString m_lastName;
public:
   CName() {}
   void SetData(LPCTSTR fn, const TCHAR mi, LPCTSTR ln)
   {
      m_firstName = fn;
      m_middleInit = mi;
      m_lastName = ln;
   }
   void GetData(CString& cfn, TCHAR& mi, CString& cln)
   {
      cfn = m_firstName;
      mi = m_middleInit;
      cln = m_lastName;
   }
   CString GetLastName()
   {
      return m_lastName;
   }
};
CName name;
CString last, first;
TCHAR middle;
name.SetData(_T("John"), 'Q', _T("Public"));
ASSERT(name.GetLastName() == _T("Public"));
name.GetData(first, middle, last);
ASSERT((first == _T("John")) && (last == _T("Public")));

See Also

Concepts

Strings (ATL/MFC)