2015-10-11 149 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

好的。这对我来说现在是有意义的。谢谢 –