#include<iostream>
using namespace std;
class aclass
{
public:
int get_a(){cout<<a;}
float get_b(){return b; }
int a=3;
private:
float b=4.12;
};
int main()
{
aclass object;
aclass *s=new aclass;
object.get_a();
cout<<endl;
cout<<object.get_b()<<endl;
cout<<s->a<<endl;
cout<<s->get_b();
return 0;
}
使用指针调用对象内容,指针名->对象属性,可以输出内容。
使用aclass *s=new aclass;开辟新的内存空间存放指针。
添加delete代表释放指针存储的内存空间。
假如未添加delete 指针名,此处没有运行析构函数,因为对应的指针(指针对象)没有结束。
假如添加delete,则会运行析构函数,输出cbd,对应的类相关的生命周期结束了。
#include<iostream>
using namespace std;
class Fun
{
public:
Fun(){cout<<"abc"<<endl;}
~Fun(){cout<<"cbd"<<endl;}
};
int main()
{
Fun * zhizhen=new Fun;
cout<<zhizhen<<endl;
delete zhizhen;
}
abc
0xc21550
cbd
--------------------------------
Process exited after 0.2769 seconds with return value 0
请按任意键继续. . .
利用构造函数创建对象时,通过指针和new来实现。其一般语法形式为:
类名 *指针变量 = new 类名[(实参表)];
例如:
Date *date1=new Date(1998,4,28);
就创建了对象(*date1)。
然后就可以借助指针变量访问对象的各种属性。