2013-06-15 3 views
1

У меня есть следующий ниже код, который работает, за исключением того, что строка POINTEE* pointee[10]; является статической, и я хочу сделать ее динамической, когда создаю класс, чтобы он мог быть любого размера.Как создать массив указателей внутри класса с переменным размером?

#include <iostream> 

class POINTEE 
{ 
    private: 

     int index; 

    public: 

    POINTEE(){} 
    POINTEE(int index) 
    { 
     this->index = index; 
    } 
    ~POINTEE(){} 
    void print_index() 
    { 
     std::cout<<index<<std::endl; 
    } 
}; 
void fill_element(POINTEE* &pointee, int index) 
{ 
    pointee = new POINTEE(index); 
} 
int main() 
{ 
    POINTEE* pointee[10];//I want to declare this within a class with a variable size instead of 10 

    for(int index = 0; index < 10; index++) 
     pointee[index] = NULL; 

    for(int index = 0; index < 10; index++) 
    { 
     POINTEE* temp_pointee; 
     fill_element(temp_pointee, index); 
     pointee[index] = temp_pointee; 
    } 

    for(int index = 0; index < 10; index++) 
     pointee[index]->print_index(); 

    for(int index = 0; index < 10; index++) 
     delete pointee[index]; 

    return 0; 
} 

Я не хочу использовать std::vector главным образом потому, что я пытаюсь создать свой собственный контейнер данных. Я также попытался сделать

#include <iostream> 

class POINTEE 
{ 
    private: 

     int index; 

    public: 

    POINTEE(){} 
    POINTEE(int index) 
    { 
     this->index = index; 
    } 
    ~POINTEE(){} 
    void print_index() 
    { 
     std::cout<<index<<std::endl; 
    } 
}; 
void fill_element(POINTEE* &pointee, int index) 
{ 
    pointee = new POINTEE(index); 
} 
int main() 
{ 
    POINTEE* pointee;// I changed this 
    pointee = new POINTEE[10];//and this and also deleted pointee below 

    for(int index = 0; index < 10; index++) 
     pointee[index] = NULL; 

    for(int index = 0; index < 10; index++) 
    { 
     POINTEE* temp_pointee; 
     fill_element(temp_pointee, index); 
     pointee[index] = temp_pointee; 
    } 

    for(int index = 0; index < 10; index++) 
     pointee[index]->print_index(); 

    for(int index = 0; index < 10; index++) 
     delete pointee[index]; 

    delete [] pointee;//I added this which maybe totally stupid! 

    return 0; 
} 

но сделал появляются другие ошибки:

C:\Documents and Settings\project5\array_of_pointers_ops\array_of_pointers_ops.cpp||In function 'int main()':| 
C:\Documents and Settings\project5\array_of_pointers_ops\array_of_pointers_ops.cpp|38|error: invalid conversion from 'POINTEE*' to 'int'| 
C:\Documents and Settings\project5\array_of_pointers_ops\array_of_pointers_ops.cpp|38|error: initializing argument 1 of 'POINTEE::POINTEE(int)'| 
C:\Documents and Settings\project5\array_of_pointers_ops\array_of_pointers_ops.cpp|42|error: base operand of '->' has non-pointer type 'POINTEE'| 
C:\Documents and Settings\project5\array_of_pointers_ops\array_of_pointers_ops.cpp|45|error: type 'class POINTEE' argument given to 'delete', expected pointer| 
||=== Build finished: 4 errors, 0 warnings ===| 
+0

«массив указателей» ** предлагается для ** реализуется как 'vector >' ... –

+0

Несомненно, это другой способ. Я знаю, что его легко реализовать как std :: vector, но почему бы не использовать стандартные указатели? – pandoragami

+2

[this] (http://stackoverflow.com/questions/381621/using-arrays-or-stdvectors-in-c-whats-the-performance-gap) et al. –

ответ

1

Я бы определенно использовать вектор себя, если вы действительно хотите сделать свой собственный вектор класса, но здесь есть некоторые проблемы с вашим код:

Следующее создает указатель, указывающий на массив из 10 объектов POINTEE. Он не указывает на указатели на объекты POINTEE.

POINTEE* pointee;// I changed this 
pointee = new POINTEE[10];//and this and also deleted pointee below 

Если вы измените строки на следующее:

POINTEE** pointee; 
pointee = new POINTEE*[10]; 

тогда ваш код по крайней мере, гораздо ближе к работе. Я не смотрел слишком близко, но я думаю, что остальная часть вашего кода была в основном компилируемой.

+0

Спасибо! Является 'delete [] pointee;' correct btw или он не нужен? – pandoragami

+0

Да, вам нужно, потому что вам нужно удалить массив указателей, которые вы выделили новым POINTEE * [10] –

Смежные вопросы