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

标签 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;
} 
我收到一个错误,因为没有默认构造函数。但这不是我的问题。有没有办法在定义时发送参数
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;
} 
但是,更好的方法是使用 vector (比如在一周内您希望数组中有 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;
} 

关于c++ - 如何在数组对象中传递参数?在 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65554555/

相关文章:

python - 打印差异大于某个值的列表元素

arrays - 在 SQL Server 中返回一个基本的 JSON 字符串数组

c++ - 生成器模式 : making sure the object is fully built

PyQt4 看不到 C++ 实例化的 QApplication

c++ - 如何将工作目录更改为程序的位置

c++ - C++中纯虚方法的重新定义

java - 我的问题的最佳 OOP 解决方案是什么?

c++ - 将回调从 C++ 转发到 ObjC

php - 如何对多维数组进行urlencode?

php - 记忆 PHP 上的链式方法