`Student students[10];` 需要 `Student` 有**默認構造函數** (無參或全參數有默認值)。若類只有帶參構造函數,編譯報錯。
#include
#include
using namespace std;
class Student {
public:
int value, score;
Student(int v, int s): value(v), score(s) {}
// 若數組定義需默認構造,取消註釋下行
// Student() : value(0), score(0) {}
};
int main() {
// 方式1: vector (推薦)
vector students;
students.emplace_back(10, 100);
students.emplace_back(20, 200);
cout << students[0].value << " " << students[0].score << endl; // 10 100
return 0;
}