简体   繁体   中英

How to pass parameters in an objects of array? in c++

class A
{
 int id;
public:
 A (int i) { id = i; }
 void show() { cout << id << endl; }
};
int main()
{
 A a[2];
 a[0].show();
 a[1].show();
 return 0;
} 

I get an error since there is no default constructor.However thats not my question.Is there a way that ı can send parameters when defining

A a[2];

A good practice is to declare your constructor explicit (unless it defines a conversion), especially if you have only one parameter. Than, you can create new objects and add them to your array, like this:

#include <iostream>
#include <string>

class A {
    int id;
    public:
    explicit A (int i) { id = i; }
    void show() { std::cout << id << std::endl; }
};

int main() {
    A first(3);
    A second(4);
    A a[2] = {first, second};
    a[0].show();
    a[1].show();
    return 0;
} 

However, a better way is to use vectors (say in a week you want 4 objects in your array, or n object according to an input). You can do it like this:

#include <iostream>
#include <string>
#include <vector>

class A {
    int id;
    public:
    explicit A (int i) { id = i; }
    void show() { std::cout << id << std::endl; }
};

int main() {
   
    std::vector<A> a;
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; i++) {
        A temp(i); // or any other number you want your objects to initiate them.
        a.push_back(temp);
        a[i].show();
    }
    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