#include<iostream>
using namespace std;
class person
{
public:
person() { cout << "无参构造的调用" << endl; }
void show()
{
cout << "年龄为:"<<18 << endl;
}
~person()
{
cout << "析构函数的调用" << endl;
}
};
void test()
{
person* p=new person;
p->show();
}
int main()
{
test();
system("pause");
return 0;
}
智能指针:托管new出来的对象的释放
#include<iostream>
using namespace std;
class person
{
public:
person() { cout << "无参构造的调用" << endl; }
void show()
{
cout << "年龄为:"<<18 << endl;
}
~person()
{
cout << "析构函数的调用" << endl;
}
};
//智能指针
class smartpoint
{
public:
smartpoint(person* person)
{
this->p = person;//指向在堆区开辟空间的地址
}
//重载->运算符号
person* operator->()
{
return this->p;
}
//重载*运算符号
person& operator*()
{
return *(this->p);
}
~smartpoint()
{
if (p != NULL)
{
delete p;
p = NULL;
}
}
private:
person* p;
};
void test()
{
/*person* p=new person;
p->show();*/
/*delete p;*/
//智能指针:托管new出来的对象的释放
smartpoint sp(new person());
//重载->运算符
//这里sp->返回的是person*
sp->show();//本质sp->->show(); 编译器简化为sp->show() sp.operator->()返回值是*person
(*sp).show();//*sp相当于-----sp.operator*(),返回值是(*person)
}
int main()
{
test();
system("pause");
return 0;
}