简体   繁体   English

如何在类中重新分配指针数组?

[英]How to reallocate array of pointers in class?

I have class Citizen { string name,address ... } and then I have class TaxRegister. 我的课程为Citizen {字符串名称,地址...},然后的课程为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; 问题是,当我必须在阵列中添加超过1000个人时;

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]' 将“公民* [[((((sizetype))+ 1)]”分配给“公民* [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. 使用std::vector<Citizen>而不是数组,问题可能会自行消失。 A standard container like std::vector manages all memory automatically for you. std::vector这样的标准容器会自动为您管理所有内存。 You will end up with no new and delete[] at all in your code. 您最终将在代码中完全没有newdelete[]

Just to give you an idea, this is what your Add_citizen function would then look like: 只是为了给您一个想法,这就是您的Add_citizen函数的外观:

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 * . 您已经在使用std::string而不是char const * That's good. 那很好。 Using std::vector instead of arrays is exactly the same improvement. 使用std::vector而不是数组是完全相同的改进。

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. 如果要坚持使用数组,只需确保数组声明中的size参数实际上是常量,而不是变量。 And then allocate a new array. 然后分配一个新数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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