Skip to content

Commit

Permalink
Merge pull request #1 from YiGOffer/重载
Browse files Browse the repository at this point in the history
Create 重载-指针运算符->
  • Loading branch information
YiGOffer authored Aug 10, 2021
2 parents b28d943 + cdc8183 commit 8bb03f6
Showing 1 changed file with 87 additions and 0 deletions.
87 changes: 87 additions & 0 deletions 重载-指针运算符->
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#include<iostream>
#include<string>
using namespace std;
//新建一个Person类
class Person
{

public:
Person()
{

};
Person(int C)
{
this->m_A = C;
};
Person(int A, int B) :m_A(A), m_B(B)
{

}
~Person()
{
cout << "P的析构函数调用" << endl;

}



void showm_A()
{
cout << "m_A=" << m_A << endl;
}
private:
int m_A;
int m_B;

};
//新建一个智能指针类
class smartPoint
{
public:
//构造函数
smartPoint(Person * p)
{
this->m_Person = p;

}

~ smartPoint()
{
cout << "S的析构函数调用" << endl;

if(this->m_Person)
{
delete m_Person;
m_Person = NULL;

}
}
//运算符->的重载,为了让sp->showm_A()能成功调用,只需让其返回一个指向Person 类型的指针。
Person* operator->()
{
return this->m_Person;
}
private:
Person * m_Person;

};




void test01()
{
Person *p1=new Person(20);
(*p1).showm_A();//解引用的调用
p1->showm_A();//使用-> 直接不用解引用 用指针就可调用showA函数
//delete p1;

//用智能指针进行释放内存
smartPoint sp(p1);
sp->showm_A();
}
int main ()
{
test01();
}

0 comments on commit 8bb03f6

Please sign in to comment.