c++ - Initialize private array with unknown number of elements (C++98) -
looks missed fundamental here, haven't worked out.
below snippet , corresponding output.
what wanted is: - declare , initialize array of structs, without knowing number of elements in advance. - ideally array , number of elements private members.
what tried:
- declared
m_member_tab[]
,m_num_members
private. - created
init()
function initializesm_member_tab[]
, calculatem_num_members
.
outcome:
m_member_tab[]
initialized ok (see below output).but inside constructor (after calling
init
),m_member_tab
corrupted.#include <iostream> using std::cout; using std::endl; class tarraytest { public: tarraytest(); private: void init(); typedef struct _tmember { int m_key; int m_val; } tmember; tmember m_member_tab[]; int m_num_members; }; tarraytest::tarraytest() { init(); cout << "ctor: number of elements = " << m_num_members << endl; for( int = 0; < m_num_members; i++ ) { cout << "ctor: " << "key " << m_member_tab[i].m_key << " - val " << m_member_tab[i].m_val << endl; } }; void tarraytest::init() { tmember m_member_tab[] = { { 1, 100 }, { 2, 200 }, { 3, 300 }, { 4, 400 }, { 5, 500 }, }; m_num_members = sizeof( m_member_tab ) / sizeof( tmember ); cout << "init: number of elements = " << m_num_members << endl; for( int = 0; < m_num_members; i++ ) { cout << "init: " << "key " << m_member_tab[i].m_key << " - val " << m_member_tab[i].m_val << endl; } } int main() { tarraytest test; }
output:
init: number of elements = 5 init: key 1 - val 100 init: key 2 - val 200 init: key 3 - val 300 init: key 4 - val 400 init: key 5 - val 500 ctor: number of elements = 5 ctor: key 5 - val 32766 ctor: key 0 - val 0 ctor: key 0 - val 0 ctor: key -1212526907 - val 32623 ctor: key 0 - val 0
this member declaration:
tmember m_member_tab[];
is not valid c++.
there additional problem in init
function, declare local variable of same name, doesn't matter: above declaration not invalid, since it's not @ end of struct doesn't make sense language extension.
instead, use std::vector
, this:
std::vector<tmember> m_member_tab;
it keeps track of array size, don't need member.
in other news, c++ directly supports initialization of instance of class. should not define ordinary function that. instead use language mechanism that, namely constructor.
you can find information constructors in tutorial , introductory c++ textbook.
the language supported mechanism has many advantages compared init
function.
oh, , seeing each item in array contain key , value, consider std::map
, or, if can use c++11 , not c++98/c03, std::unordered_map
(faster no sorted traversal of keys).
Comments
Post a Comment