类的实例化

C++中类的实例化有两种方式——在栈中实例化和在堆中实例化

在栈中实例化为静态分配内存,不需要手动回收,超出内存系统报错。

在堆中实例化为动态分配内存,需要使用delete回收。

#include<iostream>
#include<string.h>
#include<cstdio>
using namespace std;
class Person
{
public:
    int age;
    string name;
    int sex;
public:
    Person(int age,int sex,string name)
    {
        this->age=age;
        this->sex=sex;
        this->name=name;
    }
    int getAge();
    int getSex();
    string getName();
};
int Person::getAge()
{
    return this->age;
}
int Person::getSex()
{
    return this->sex;
}
string Person::getName()
{
    return this->name;
}
ostream &operator<<(ostream &os,Person &p)
{
    os<<p.getAge()<<" "<<p.getSex()<<" "<<p.getName();
    return os;
}
ostream &operator<<(ostream &os,Person *p)
{
    os<<p->getAge()<<" "<<p->getSex()<<" "<<p->getName();
    return os;
}
int main()
{
    //在堆中实例化
    Person *p1 = new Person(1,1,"name1");
    //在栈中实例化
    Person p2(2,2,"name2");
    cout<<p1<<endl;
    delete p1;
    cout<<p2<<endl;
}

在堆中实例化需要用指针来接收实例化的对象。

posted @ 2016-11-27 21:05  康小武  阅读(241)  评论(0编辑  收藏  举报