首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 類數組定義:動態分配避免默認構造函數限制

     編輯:程式設計疑難解答

問題

`Student students[10];` 需要 `Student` 有**默認構造函數** (無參或全參數有默認值)。若類只有帶參構造函數,編譯報錯。

解決方案

  1. 提供默認構造函數:`Student() {}` 或 `Student(int v=0, int s=0):value(v),score(s){}`
  2. 動態分配 (推薦):
    `Student* students = new Student[10];` (仍需默認構造函數)
    更靈活:`std::vector students(10);` 或 `std::vector students; students.reserve(10);` 後 `push_back` 構造。
  3. 初始化列表 (C++11):
    `Student students[3] = { Student(1,100), Student(2,90), Student(3,80) };`

代碼示例


#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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved