"AFTER SOLVED" EDIT:
This technique gives the ability to dynamicaly create an object each time and send it to a vector.
By this way you wont any more have to pre-create an Array of 100 objects and keep an i pointing the last of the objects used until now, neither transfer it from func to func along the Object Array it self
---------------------------------------------------------------------------------------------------------------------------------------
This is NOWHERE on the WEB until my search sizei.
I want to new a object and put it to a vector
1 2 3
|
vector <CLIENT *> vCLIENT;
vCLIENT.push_back(new CLIENT(1,100)); //CLIENT(int ID, int credit){...}//constr
vCLIENT.push_back(new CLIENT(2,100));
|
All ok BUT WHEN I
|
cout<<vCLIENT[0].getID(); //class CLIENT::int getID(){return ID;}
|
Says "...which is of non class type 'CLIENT*'"
if i put
|
cout<<*vCLIENT.getID(); //class CLIENT::int getID(){return ID;}
|
Says "...has no member named 'getID' "
Seems logicless
Please help couldnt find it anywhere in tens of of forum and hours search.
--------------------------------------------------------------------------------------------------------------------------------------
SOLUTION ("AFTER SOLVED" EDIT)
The . has higher precedence than *, so what you need is (*vCLIENT[0]).getID(). To make it less of a mess, there is ->. Then it is vCLIENT[0]->getID().
(by hamsterman )
1 2 3 4 5 6 7 8 9
|
vector <CLIENT *> vCLIENT;
vCLIENT.push_back(new CLIENT(0,100)); //CLIENT(int ID, int credit){...}//Class's construcor
vCLIENT.push_back(new CLIENT(1,150));
cout<<"\nID:" <<vCLIENT[0]->getID(); //class CLIENT::int getID(){return ID;}
cout<<"\nCredit:"<<vCLIENT[0]->getCredit();
cout<<"\nID:" <<vCLIENT[1]->getID();
cout<<"\nCredit:"<<vCLIENT[1]->getCredit();
|
The use of pointers can also be avoided along with -> and use . instead. A debate on the need or not of pointers has taken place
Pointers may be used when:
_ You don't have the ownership of the objects, but you are referencing them.
_ You want to use polymorphism
_ The class doesn't have a copy constructor (maybe the new standard have something to say about this)
(by ne555 & moorecm)