Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an array of class objects whose constructor require few arguments?

I've read about solution const A a[3] = { {0,0}, {1,1}, {2,2} }, but in my program const can't be used:

class Paper: public PaperQueue{  
  ...
  protected:
    typedef int (Utils::*funcPtr) (int, int); //I use external function there
    funcPtr p;                               
    Utils* fptr; 
  public:
    int pricefunc(){     
      addprice = (fptr->*p) (t,price);
    }

    Paper(int n, unsigned int pr):PaperQueue(n){         
       ...
       p=&Utils::commonpricefunc;    
    }
    void Put(int a){ 
       ...
    }
  ...
}    

class Bank{ 
  ...
  void Buy(Paper &p){
   (/*this function modifies many parameters in 'p'*/)
  ...
  }
  ...
}

int main(){
Bank B;    
int pn=5;
/* ? */ const Paper p[pn] = {{5,15},{5,15},{5,15},{5,15},{5,15}}; /* ? */
int paperloop=0;
...
p[paperloop].Put(p[paperloop].addprice);
B.Buy(p[paperloop]);
...

That gives me a LOT of errors(with pricefunc(),Put(),Buy(),...), or just "variable-sized object ‘p’ may not be initialized". Is there any way to make this array work? (Everything works fine if not to pass any parameters to constructor!)

like image 443
Slowpoke Avatar asked Nov 23 '12 03:11

Slowpoke


1 Answers

You can't use initializer lists for classes (non-PODs) because that would bypass the call to the constructor. You'll have to change it to a POD or use std::vector in the following ways:

If the class is copyable, as it appears to be, you can create a std::vector and fill it with the values you want:

const vector<Paper> papers(5, Paper(5, 15));

If you want to initialize it with different values, you can use an initializer list, but this is only supported in C++11:

const vector<Paper> papers = {Paper(1, 1), Paper(2, 2)};

Without C++11, you'll have to add the elements one by one, but then you can't make the vector const:

vector<Paper> papers;
papers.push_back(Paper(1, 1));
papers.push_back(Paper(2, 2));
like image 69
user1610015 Avatar answered Nov 15 '22 07:11

user1610015