I have class Citizen { string name,address ... } and then I have class TaxRegister.

class TaxRegister
{
public:
    bool Add_citizen ( const string& name, const string& addr );
private:
    static const int m_Size=1000;
    int m_Index,m_IncrementedSize;
    Citizen * m_People[m_Size];
};

bool TaxRegister::Add_citizen( const string& name, const string& addr )
{
....
    m_People[m_Index++] = new Citizen( name,addr ); 
}

The problem is, when I have to add more then 1000 people into my array;

I tried to do this:

Citizen *tmp[m_IncrementedSize*=2];
for (int i=0; i < m_Index; i++ )
    tmp[i]=m_People[i];
delete [] m_People;
m_People=tmp;
m_IncrementedSize*=2;

But the compilator gives me this:

incompatible types in assignment of ‘CCitizen* [(((sizetype)) + 1)]’ to ‘CCitizen* [1000]’

Does anybody know how to fix it ? Thank you.

有帮助吗?

解决方案

Use std::vector<Citizen> instead of an array and the problem will likely disappear by itself. A standard container like std::vector manages all memory automatically for you. You will end up with no new and delete[] at all in your code.

Just to give you an idea, this is what your Add_citizen function would then look like:

void TaxRegister::Add_citizen( const string& name, const string& addr )
{
    m_People.push_back(Citizen(name, addr));
}

You are already using std::string instead of char const *. That's good. Using std::vector instead of arrays is exactly the same improvement.

其他提示

If you want to stick to arrays, just make sure that the size parameter in the array declaration is actually a constant, rather than a variable. And then allocate a new array.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top