error using CArray

2019-01-19 23:11发布

问题:

So, I am trying to use CArray like this :

 CArray<CPerson,CPerson&> allPersons;
   int i=0;
   for(int i=0;i<10;i++)
   {
      allPersons.SetAtGrow(i,CPerson(i));
      i++;
   }

But when compiling my program, I get this error :

"error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject' c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtempl.h"

I don't even understand where this is coming from.

HELP!

回答1:

The error you are getting is because you are trying to use a CArray as a return value from what I can gather. If you change it from returning a CArray to taking a reference parameter instead, that will compile.

Try this:

class CPerson
{
public:
    CPerson();
    CPerson(int i);
    void operator=(const CPerson& p) {}
private:
    char* m_strName;
};

CPerson::CPerson()
{}

CPerson::CPerson(int i)
{
    sprintf(m_strName,"%d",i);
}

void aFunction(CArray<CPerson,CPerson&> &allPersons)
{
    for(int i=0;i<10;i++)
    {
        allPersons.SetAtGrow(i,CPerson(i));
        i++;
    }
}


回答2:

Are you using any of the Copy constructor or assignment operator of CObject ? ( CArray is derived from CObject)

For instance:

 CArray<CPerson,CPerson&> allPersons;  

//do something

// This gives the error C2248, cannot access Copy constructor of CObject.
CArray<CPerson,CPerson&> aTemp = allPersons;

OR

Are you doing this?

CArray<CPerson,CPerson&> allPersons; 
...
CArray<CPerson,CPerson&> aTemp;

//Error, as Assignment operator is private
aTemp = allPersons;

EDIT: If you want to copy the elements in CArray, write a helper method CopyArray() and copy the elements manually.

CopyArray(sourceArray, DestArray&)
{
 for each element in SourceArray
 add the element to DestArray.
}


回答3:

Do you mean to say CArray<CPerson> allPersons; ? I don't know how leaving out the contained type would lead to the reported error, but...



回答4:

Is CPerson derived from CObject? Does it have a private constructor? Your use of SetAtGrow() seems correct to me otherwise.

If that doesn't work, you might try falling back to using the Add() function, as your loop doesn't seem to require SetAtGrow().



回答5:

I'm not totally sure of what your problem was, but take also a look at this: Microsoft CObject derived class specifications.

You might want to add this code:

class Person
{
    // ...
    Person( const Person& src );
}

Person::Person( const Person& src ){ Person();*this = src; }

Hope it helps for the future.



回答6:

If CPerson is a complex object, maybe you should consider using pointers

   CArray<CPerson*,CPerson*> allPersons;
   int i=0;
   for(int i=0;i<10;i++)
      allPersons.SetAtGrow(i,new CPerson(i));

Don't forget to delete your array's content once it's not needed anymore

   for(int i=0;i<allPersons.GetSize();i++)
      delete allPersons.GetAt(i);


标签: c++ mfc