当前位置: 代码迷 >> 综合 >> C++,类的对象 (栈上的和堆上的),语法练习
  详细解决方案

C++,类的对象 (栈上的和堆上的),语法练习

热度:69   发布时间:2024-01-19 15:40:00.0
#include <iostream>
#include <string>
using namespace std;
// 定义一个类 Student
class Student
{
private:
string name;
int    age;
string address;
public:
// 存
void setname(string s){	name = s;}
void setage(int y){age = y;	}
void setaddress(string add){address = add;}
// 取
string getname(){return name;}
int getage(){return age;}
string getaddress(){return address;}
protected:
};
//--- main -------------
int main(void)
{
Student x; // x在栈上,快,容量小,自动释放,自动清理
x.setname("柳絮飘");
x.setage(22);
x.setaddress("学明路115号");     
cout<<"sizeof(x) = "<<sizeof(x)<<endl;  //36 字节
cout<<"姓名: "<<x.getname()<<"              年龄: "<<x.getage()<<"           住址: "<<x.getaddress()<<endl;
cout<<endl<<endl<<endl;
Student *p = NULL;
p = new Student();  // p 在堆上申请的空间   无名对象 
p->setname("王志民");
p->setage(21);
p->setaddress("建设路22号");
cout<<"sizeof(p) = "<<sizeof(p)<<endl;  //4字节	 
cout<<"姓名: "<<p->getname()<<"              年龄: "<<p->getage()<<"           住址: "<<p->getaddress()<<endl; 
cout<<endl<<endl<<endl;
Student *s = NULL;
s = &x;            // s 指向栈里的对象 x 
cout<<"sizeof(s) = "<<sizeof(s)<<endl;  //4字节	 
cout<<"姓名: "<<s->getname()<<"              年龄: "<<s->getage()<<"           住址: "<<s->getaddress()<<endl; 
// --------------------
return 0;
}


 

 

  相关解决方案