【问题标题】:How to pass parameters in an objects of array? in c++如何在数组对象中传递参数?在 C++ 中
【发布时间】:2021-04-09 18:23:58
【问题描述】:
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];

【问题讨论】:

  • A a[2] = { 1, 5 }; 应该可以工作。
  • 或者如果构造函数是explicitA a[2]{ A(1), A(5) };

标签: c++ arrays oop constructor


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2012-10-06
  • 2013-04-08
  • 1970-01-01
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多