how to initialize array of objects during declaration?
Feb 4, 2014 at 1:06pm UTC
i created a class :
header:
1 2 3 4 5 6 7 8 9
class employee{
char name[20];
unsigned int salary;
public :
employee();
employee(const char *,unsigned int );
void init(const char *,unsigned int );
void print();
};
cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <iostream>
#include <string>
#include "class.h"
using namespace std;
employee::employee(){};
employee::employee(const char * ename,unsigned int salary)
{
strcpy_s(name,20,ename);
this ->salary=salary;
}
void employee::init(const char * ename, unsigned int salary)
{
strcpy_s(name,20,ename);
this ->salary=salary;
}
void employee::print()
{
cout<<"name: " ;
int i=0;
while (name[i]!='\0' )
{
cout<<name[i];
i++;
}
cout<<"\n" <<"salary: " <<salary<<endl;
}
now im asked to create an array of 3 objects (
employee emp[3]
),
and initialize its members during declaration.
can anyone plz explain to me how can i do it??
Feb 4, 2014 at 1:30pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
struct X
{
X( int i, char c ) : i( i ), c( c ) { }
void print() { std::cout << i << " " << c << std::endl; }
private :
int i;
char c;
};
int main()
{
X x[ 3 ] = { { 23, 'c' }, { 12, 'c' }, { 23, 'c' } }; // <==== HERE ====>
for ( auto & i : x )
i.print();
}
EDIT
And i suggest to use
std::string instead of c-strings
Last edited on Feb 4, 2014 at 1:34pm UTC
Topic archived. No new replies allowed.