看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) win10 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) Dev C++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 這個class目的是輸入兩個數列 最後會印出交集跟聯集 交集聯集的函式就沒貼了 主要是class宣告看不太懂 都寫在程式碼裡 希望有人能幫忙解惑 謝謝 餵入的資料(Input): class Set { private: int *s, n; public: Set(int _n = 1) {//1. 這邊應該是同載? 為何這邊要設1呢 n = _n; s = new int[n]; } Set(int *a, int _n) { setSet(a, _n); } void setSet(int *a, int _n) { n = _n; s = new int[n]; for (int i = 0; i < n; i++) s[i] = a[i]; } int getN() { return n; } int getSet(int *a) { for (int i = 0; i < n; i++) a[i] = s[i]; return n;//2. 為何這邊只回傳n 而不是整個s 所以這個函式是為了得到n? } string str() { ostringstream out; // output string stream out << "{"; for (int i = 0; i < n - 1; i++) out << s[i] << ", "; out << s[n - 1] << "}"; return out.str(); } }; Set read_set(char *line) { int a[SIZE], i = 0; char *p = strtok(line, " ");//3. 這個*p是什麼? 感覺不是指標 a[i++] = atoi(p); //4. a本來就是int 為何這邊還要atoi呢 while((p = strtok(NULL, " ")) != NULL) a[i++] = atoi(p); int n = i; return Set(a, n); } 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.114.236.67 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1496585957.A.A94.html
fuhu66: int getSet(int *a) 是為了不讓你操作private成員 06/04 22:28
noodleT: 1. 可以不要預設1 06/04 23:20
noodleT: 2. s 已經透過 a 回傳了,程式裡面不是寫 a[]=s[] 嗎 06/04 23:22
colako: 猜你初學在看學長的code,直接問會的比較快,還要練習char* 06/04 23:23
noodleT: 3. 他是指標沒錯,參考 http://www.cplusplus.com/refere 06/04 23:26
noodleT: nce/cstring/strtok/ 06/04 23:26
noodleT: 4. atoi 是用在 p 上,跟 a[] 是不是整數沒有關係。上面 06/04 23:29
noodleT: 的網站也能找到atoi用法 06/04 23:29
james1022jk: 2.的寫法我覺得怪怪的,然後有new沒delete[] 06/04 23:30
noodleT: 2.還好吧?像一樓說的避免存取私有成員 06/04 23:34
james1022jk: a的size小於n應該就會有問題吧 06/04 23:35
noodleT: 在程式內重 new a 也怪怪的,姑且相信外面會提供足夠的記 06/04 23:41
noodleT: 憶體? 06/04 23:41
james1022jk: 只能這樣信了XD 06/04 23:42
arashi2014: 請問3的地方 我知道是用空隔切開 不過*p到底該如何理 06/04 23:47
arashi2014: 解呢 06/04 23:47
james1022jk: 你認為char *p跟char* p是不一樣的? 06/05 00:00
arashi2014: 一樣的吧 所以p應該是指向整數還是陣列呢? 06/05 00:15
arashi2014: 我覺得是指向整數陣列 但看到atoi(p)又很疑惑這樣的 06/05 00:16
arashi2014: 用法 06/05 00:16
james1022jk: p是指向字元陣列 06/05 00:19
steve1012: Atoi是運作在p上面 p是car pointer 你的疑惑是啥 06/05 02:16
arashi2014: a存的是isn 為何p要設成char呢 06/05 02:45
arashi2014: P指向陣列 那atoi(p) 的p指的是p[i]嗎還是? 06/05 02:46
a29022792: 看起來readset 是要讀取不定量數字到陣列裡面 06/05 03:15
a29022792: p是指標 你先去查strtok在幹嘛 06/05 03:17
a29022792: size不知道哪裡來的 06/05 03:19
a29022792: 你去看看strtok怎麼實作的 然後line會是一個用空格隔開 06/05 03:23
a29022792: 的字串 字串內容是數字 像是1 2 33這樣 06/05 03:23
noodleT: atoi 是將字元陣列轉成整數 06/05 07:02
noodleT: 他輸入是 char* 輸出 int ,並沒有規定輸入、輸出要一樣 06/05 07:03
noodleT: strtok 這裡是用空白鍵去切割沒錯,他回傳是字元陣列 06/05 07:08
noodleT: 如:“123”,請不要把 “123”和123當作是相同東西 06/05 07:08
noodleT: “123”是字元陣列,123是int 06/05 07:09