[問題] class的記憶體宣告問題
不好意思我是C++新手...
有個class長這樣
class test{
public:
test();
~test();
private:
test *node;
};
test::test()
{
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), 來自: 1.161.50.85
※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1411298554.A.447.html
※ 編輯: kdok123 (1.161.50.85), 09/21/2014 19:30:36
→
09/21 19:39, , 1F
09/21 19:39, 1F
推
09/21 19:42, , 2F
09/21 19:42, 2F
→
09/21 19:43, , 3F
09/21 19:43, 3F
推
09/21 20:04, , 4F
09/21 20:04, 4F
→
09/21 20:15, , 5F
09/21 20:15, 5F
→
09/21 21:55, , 6F
09/21 21:55, 6F
→
09/21 22:51, , 7F
09/21 22:51, 7F
→
09/21 22:51, , 8F
09/21 22:51, 8F
→
09/21 22:51, , 9F
09/21 22:51, 9F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):