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
對象。因此,它肯定會在堆中得到存儲。但它的屬性age
和name
將在哪裏獲得存儲?
既然你也用'new'分配'age'和'name',它也會被分配到堆上。 –
@JameyD:是的,我知道,但「年齡」和「名稱」指針會佔據內存?正如你所說的,他們的記憶塊肯定會堆積如山。 –
是指針本身存儲在堆中。 – 0x499602D2