一、栈区创建对象
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
class Student{
string name = "小明";
public:
string Getname(){return name;}
};
int main()
{
Student stu1;
cout << "name:" << stu1.Getname() << endl;;
return 0;
}
二、静态区创建对象
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
class Student{
string name = "小明";
public:
string Getname(){return name;}
};
//静态区存储
static Student stu1;
int main()
{
cout << "name:" << stu1.Getname() << endl;;
return 0;
}
三、堆区创建对象
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
class Student{
string name = "小明";
public:
string Getname(){return name;}
};
int main()
{
//堆区创建
Student* stu1 = new Student();
cout << "name:" << stu1->Getname() << endl;
delete stu1;
return 0;
}
这里的new和delete实际上是对C语言中的malloc和free的封装,简单理解。
1724

被折叠的 条评论
为什么被折叠?



