如何在数组的对象中传递参数?在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;
} 

我得到了一个错误,因为没有默认的构造函数。然而,这不是我的问题。有没有一种方法可以在定义时发送参数

A a[2];

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

#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;
} 

然而,更好的方法是使用向量(例如,在一周内,您希望数组中有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;
} 

最新更新