2015-10-11 188 views
0

我有點困惑我的下面的簡單程序的某些成員將獲得存儲?堆棧和堆棧內存存儲在C++

#include <iostream> 

using namespace std; 

class Human 
{ 
    public: 
     int *age; //where will it get storage? 
     string *name; //where will it get storage? 

     Human(string name, int age) 
     { 
      this->name = new string; //string will got into heap 
      this->age = new int; //int will go into heap 

      *(this->name) = name; 
      *(this->age) = age; 
     } 

     void display() 
     { 
      cout << "Name : " << *name << " Age : " << *age << endl; 
     } 

     ~Human() 
     { 
      cout << "Freeing memory"; 
      delete(name); 
      delete(age); 
     } 
}; 

int main() 
{ 
    Human *human = new Human("naveen", 24); //human object will go into heap 
    human->display(); 
    delete(human); 
    return 0; 
} 

我創建使用new操作類Human對象。因此,它肯定會在堆中得到存儲。但它的屬性agename將在哪裏獲得存儲?

+1

既然你也用'new'分配'age'和'name',它也會被分配到堆上。 –

+0

@JameyD:是的,我知道,但「年齡」和「名稱」指針會佔據內存?正如你所說的,他們的記憶塊肯定會堆積如山。 –

+0

是指針本身存儲在堆中。 – 0x499602D2

回答

4

的成員變量agename它們分別指向intstring將取決於你如何創建Human類的一個對象被存儲在堆或堆。

存儲在堆棧上:

Human human("naveen", 24); // human object is stored on the stack and thus it's pointer members `age` and `name` are stored on the stack too 

保存在堆上:

Human *human = new Human("naveen", 24); // human object is stored on the heap and thus it's pointer members `age` and `name` are stored on the heap too 

您提供的代碼:

Human *human = new Human("naveen", 24); //human object will go into heap 

//human object will go into heap僅僅指Human類的所有成員存儲在堆上。

+0

好的。這對我來說現在是有意義的。謝謝 –