[問題] 二維陣列default constructor問題

看板C_and_CPP (C/C++)作者 (AhMo)時間9年前 (2016/11/05 20:18), 編輯推噓2(209)
留言11則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Win7 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) Visual studio 2013 問題(Question): 要建一個class matrix 能夠透過constructor生成二維陣列 有無參數跟有參數兩種constructor class matrix { private: int** m; int size; public: //parameter constructor matrix(int s) { size = s; m = new int*[size]; for (int i = 0; i<size; i++) m[i] = new int[size]; } //default constructor matrix() { m = new int*[size]; for (int i = 0; i<size; i++) m[i] = new int[size]; } } ----------------------------------------- 在主程式裡頭不曉得要怎麼達到下面這種效果 matrix* mArr1 = new matrix[10]; //calling default constructor matrix mArr2[5]; //calling default constructor 資料成員雖然有size可是沒初值用在default constructor上面無作用 要做像是 matrix mArr2[5]這樣事情時就無法 感覺matrix(){}有點像是多打的 想了很久不知道怎麼解決 C++新手請求各位高手幫忙@@ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.241.16.145 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1478348296.A.FCD.html

11/05 21:00, , 1F
看不太懂你想要幹嘛
11/05 21:00, 1F

11/05 21:01, , 2F
Marr1 跟marr2有啥關聯
11/05 21:01, 2F

11/05 21:04, , 3F
幾個看到的問題1.size 用size_t 2. 為何不用vector 3.
11/05 21:04, 3F

11/05 21:04, , 4F
值沒有出始化
11/05 21:04, 4F

11/05 21:05, , 5F
Matrix 剛開始會是一堆garbage
11/05 21:05, 5F

11/05 21:59, , 6F
operator overloading也沒辦法做到你想要的樣子吧?
11/05 21:59, 6F

11/05 21:59, , 7F
而且你希望的matirx[10]應該是一個10x10 matrix?
11/05 21:59, 7F

11/05 22:00, , 8F
如果是的話你直接把你希望的樣子改成類似new matrix(10)
11/05 22:00, 8F

11/05 22:01, , 9F
和mArr2(5) 看起來應該就會動了 有錯請指正 thx
11/05 22:01, 9F

11/05 22:02, , 10F
我這種寫法等於你的default constructor是沒有用的
11/05 22:02, 10F

11/05 22:02, , 11F
不過你的default constructor的size也未定義 也是不能用
11/05 22:02, 11F
文章代碼(AID): #1O7Su8_D (C_and_CPP)
文章代碼(AID): #1O7Su8_D (C_and_CPP)