简体   繁体   中英

How to create “CArray<CArray<CString>>& results” in MFC?

I'm an unable to create a 2D array in MFC as per the code "CArray>& results". Code:

CArray<CArray<CString>> res;

    CArray<CString>strArray1;

    strArray1.Add(L"Ali");
    strArray1.Add(L"Ahmed");
    strArray1.Add(L"Mark");

    CArray<CString>strArray2;

    strArray2.Add(L"1");
    strArray2.Add(L"2");
    strArray2.Add(L"3");

res.Add(strArray1);
res.Add(strArray2);

Error after execution: error C2248: 'CObject::operator =' : cannot access private member declared in class 'CObject'

This should be done without overriding copy and equals method in CArray, instead is there any way where I wouldn't need those indirectly like some method of CArray that can be leveraged.

The signature for CArray::Add() is

INT_PTR Add(ARG_TYPE newElement);

You'll notice that the newElement argument is passed by value. This means the element type must be copy-constructible, which CObject s are not. This isn't particularly well-documented; parts of the CMap documentation state that the value type of the map has to be copy-constructible, so we can assume the rest of the API was designed similarly.

This question explains why CObject s are not copy-constructible.

So what can you do? You have several options.

  • Switch to using CArray<CArray<CString> *> — store the inner dimension arrays as pointers instead of values; this also saves memory
  • Switch to using CTypedPtrArray<CObjArray, CArray<CString> *> , which allows you to use CObArray instead, and still be type-safe
  • Switch to using standard C++ containers, namely std::vector<std::vector<CString> > as @PaulMcKenzie suggested above. CString is not a CObject , so you can use it directly. Alternatively, if you are just using CString as a wrapper around C strings, you can also switch to std::string or std::wstring , but only do this if you know what you are doing.
  • Of course, if you need the inner dimension to be a CArray , you can also do std::vector<CArray<CString> *> . As usual, the pattern requires you to use pointers — you can't just say std::vector<CArray<CString> > for the same reason as above ( std::vector requires copy-constructibility).
  • Use a one-dimensional array ( CArray<CString> or std::vector<CString> or whatever) of size m * n (where m is the size of the inner dimension). In that case, arr[i][j] in your code snippet is the same as arr[i * m + j] . In fact, this is what multidimensional arrays boil down to, as textbook examples on matrix multiplication in C will show. (Thanks to @IInspectable for reminding me of this one.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM