简体   繁体   中英

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 by creating objects this way. If only one object would be created, the code would look like this:

Class object("Text", val);

The rest is managed by the constructor. Thanks in advance for your ideas!

In C++98:

Class object[3] = {Class("Text1", val1), Class("Text2", val2), Class("Text3", val3)};

But this requires Class to be copy-constructible.

In C++11 it's a bit simpler and, more importantly, doesn't require Class to be copy-constructible:

Class object[3] = {{"Text1", val1}, {"Text2", val2}, {"Text3", val3}};

If you have more than a few objects, it's better to use std::vector and push_back() / emplace_back() .

you variable object is not an instance of Class but an array.
so you could use an array initialization, please look the sample 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM