我对以下简单程序的某些成员将获得存储的位置感到有点困惑?
#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;
}
我使用Human
运算符创建了一个类new
对象。因此,它肯定会在堆中存储。但是它的属性age
和name
将在哪里获得存储空间?
答案 0 :(得分:4)
分别指向age
和name
的成员变量int
和string
将存储在堆或堆栈上,具体取决于您创建对象的方式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
类的所有成员都存储在堆上。