Re: [問題] class的記憶體宣告問題

看板C_and_CPP作者 (「雄辯是銀,沉默是金」)時間9年前 (2014/09/21 20:08), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《kdok123 (小天)》之銘言: : 不好意思我是C++新手... : 有個class長這樣 : class test{ : public: : test(); : ~test(); : private: : test *node; : }; : test::test() : { : node = new test; : } test::test() { cout << "i: " << endl; node = new test; } 你改成這樣跑跑看, 也許就知道了。 : test::~test() : { : free(node); : } : int main() : { : test *head = new test;//這個地方就爆掉了 : return 0; : } : 大概跑了一次知道是constructor裡不能再new了,不過為什麼呢? : 我只是想要把物件指標head裡的node給定一個new的空間而已呀? : 大概有想過應該是我外面new了一個test的容量 : 可是裡面又要new一個test,這樣雙倍的test他會吃不消 : 所以我又試了 : test *head = new test[2]; : 但還是不行 : 最後是把constructor拿掉,把test *node宣告成public : 從main裡用物件去申請node的空間才行 : 想請問這中間的空間分配問題出在哪裡了?? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 58.114.144.73 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1411301314.A.D99.html

09/21 21:02, , 1F
會出現很多的 i:
09/21 21:02, 1F

09/21 21:53, , 2F
謝謝! 我知道了! 又耍笨了...
09/21 21:53, 2F
文章代碼(AID): #1K7h_2sP (C_and_CPP)
文章代碼(AID): #1K7h_2sP (C_and_CPP)