每当我们从一个类创建一个对象时,它就会占用更多空间的堆上创建,而堆栈中占用其内存的结构变量则会占用更多空间。如果我创建一个Person类和一个struct P,具有相同的属性,那么它应该证明我刚才所说的内容。请检查下面的代码片段2:什么占据更多的空间:对象还是结构?
#include <iostream.h>
#include <conio.h>
#include <string>
using namespace std;
class Person{
int age;
string hair_color;
float height;
public:
Person::Person(int n)
{
age = n;
}
int Person::getAge()
{
return age;
}
};
struct P{
int age;
};
main()
{
Person person(45);
//Person *person = new Person(45);
P myPerson;
cout<<sizeof(person)<<endl;
cout<<sizeof(myPerson)<<endl;
//cout<<"Age: "<<person->getAge();
getch();
}
当我写这篇文章的代码:
#include <iostream.h>
#include <conio.h>
#include <string>
using namespace std;
class Person{
int age;
string hair_color;
float height;
public:
Person::Person(int n)
{
age = n;
}
int Person::getAge()
{
return age;
}
};
struct P{
int age;
};
main()
{
// Person person(45);
Person *person = new Person(45);
P myPerson;
cout<<sizeof(person)<<endl;
cout<<sizeof(myPerson)<<endl;
getch();
}
请纠正我,如果我错了,这里有关对象和refernces。我想从我的代码知道什么占据更多的空间:对象或结构?
“每当我们从类创建一个对象,它是在堆上创建”。 “与结构变量相比,占用更多空间” - 错误。“在堆栈上占据了内存” - 错误。大错特错。你显然根本不理解物体。了解更多C++,不用担心内存使用情况。 – 2013-10-26 16:49:09
非常感谢。感谢您的评论。 –