-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from YiGOffer/重载
Create 重载-指针运算符->
- Loading branch information
Showing
1 changed file
with
87 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} |