选自CSDN:bitcarmanlee
http://t.csdn.cn/vd2rN
三种实例化方式
创建类
class Person {
private:
int age;
string name;
public:
Person() {
cout<<"this is construct~";
}
Person(int age, string name) {
this->age = age;
this->name = name;
cout<<"name is: "<<name<<", age is: "<<age<<endl;
}
};
隐式创建
Person p1;
cout<<endl;
Person p2(18, "lili");
cout<<endl;
显示创建
Person p3 = Person();
cout<<endl;
Person p4 = Person(16, "xx");
cout<<endl;
用new创建
Person *p5 = new Person();
cout<<endl;
Person *p6 = new Person(14, "yy");
三种方式的区别
- new出来的对象必须要用指针接收,并且需要显式delete销毁对象释放内存。
- 内存位置不同。
- 对于隐式声明 Person p1; p1对象位于栈空间。
- Person *p5 = new Person(); p5对象位于堆空间。
- 内存分配时间不同
- 使用隐式创建对象的时候,创建支出就已经分配了内存。
- 而使用new的方式,如果对象没有初始化,此时没有分配内存空间,也无法delete。
Person *p = NULL;
delete p;
上述语句如果执行,会有各种意想不到的情况发生。
- 隐式声明的对象是局部变量,出了函数就没有了。而new出来的指针对象可以在方法之间传递,且该指针对象所指向的堆中的对象实例仍然存在。
- 频繁调用场合并不适合new,就像new申请和释放内存一样。