C++智能指针简单案例
智能指针其实就是对->和*运算符重载的应用
#include <iostream>
#include <cstring>
using namespace std;
class Person{
public:
Person(int age){
cout << "有参构造函数调用" << endl;
this->m_age = age;
}
void showAge(){
cout << "年龄:" << this->m_age << endl;
}
~Person(){
cout << "析构函数调用" << endl;
}
private:
int m_age;
};
//智能指针 用来托管new出来的对象的释放
class SmartPointer{
public:
SmartPointer(Person* person){
cout << "SmartPointer" << endl;
this->person = person;
}
//重载指针运算符
Person* operator->(){
return this->person;
}
//重载*运算符
Person& operator*(){
return *this->person;
}
~SmartPointer(){
if(this->person != NULL){
cout << "~SmartPointer" << endl;
delete this->person;
this->person = NULL;
}
}
private:
Person* person;
};
void test01(void){
// Person* p = new Person(18);
// delete p;
SmartPointer sp = SmartPointer(new Person(18));
sp->showAge(); //sp->->showAge(),编译器简化为sp->showAge()
(*sp).showAge();
}
int main(int argc, char* argv[]){
test01();
system("pause");
return 0;
}
还没有评论,来说两句吧...