如何在数组对象中传递参数?在 C++

Kad*_*rım 6 c++ arrays oop constructor

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;
} 
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,因为没有默认构造函数。但这不是我的问题。有办法吗?定义时可以发送参数

A a[2];
Run Code Online (Sandbox Code Playgroud)

Emi*_*nem 0

一种好的做法是显式声明构造函数(除非它定义了转换),特别是当您只有一个参数时。然后,您可以创建新对象并将它们添加到数组中,如下所示:

#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;
} 
Run Code Online (Sandbox Code Playgroud)

然而,更好的方法是使用向量(假设一周内您需要数组中的 4 个对象,或者根据输入需要 n 个对象)。你可以这样做:

#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;
} 
Run Code Online (Sandbox Code Playgroud)