[英]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;
}
我收到一個錯誤,因為沒有默認構造函數。但這不是我的問題。有沒有一種方法可以在定義時發送參數
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 object)。 你可以這樣做:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.