C ++: objects created via array, but how to pass parameters?
It would be great if you could help me here: I create objects as an array
Class object[3];
but I don't know how to pass parameters while creating objects this way. If only one object is created, the code will look like this:
Class object("Text", val);
The rest is controlled by the constructor. Thanks in advance for your ideas!
source to share
In C ++ 98:
Class object[3] = {Class("Text1", val1), Class("Text2", val2), Class("Text3", val3)};
But this requires that it Class
be copyable.
In C ++ 11, this is a bit simpler and, more importantly, does not require it to Class
be copyable:
Class object[3] = {{"Text1", val1}, {"Text2", val2}, {"Text3", val3}};
If you have multiple objects, it is better to use std::vector
and push_back() / emplace_back()
.
you variable object is not an instance of a class but an array.
so you can use array initialization, see example below:
#include "stdafx.h"
using namespace std;
class Class {
public:
std::string val2;
int val2;
Class(std::string val1, int param2){
val1 = param1;
val2 = param2;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int a[3] = {1, 2, 3};
for(int i=0; i<3; i++){
printf("%i\n", a[i]);
}
Class object[3] = {Class("Text1",10), Class("Text2",20), Class("Text3",30)};
for(int i=0; i<3; i++){
printf("%s %i\n", object[i].val1, object[i].val2);
}
return 0;
}
source to share