一、程序及输出
1.1 重载->运算符
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
cout << "Person的有参构造调用" << endl;
this->m_Age = age;
}
void showAge()
{
cout << "年龄为: "<< this->m_Age << endl;
}
~Person()
{
cout << "Person的析构调用" << endl;
}
int m_Age;
};
class SmartPoint
{
public:
SmartPoint(Person * person)
{
this->m_person = person;
}
//重载->运算符
Person * operator->()
{
return this->m_person;
}
~SmartPoint()
{
if (this->m_person)
{
delete this->m_person;
this->m_person = NULL;
}
}
private:
Person * m_person;
};
void test01()
{
//利用智能指针 管理 new出来的person的释放操作
SmartPoint sp(new Person(18));
sp->showAge(); // 本质sp->->showAge(); 编译器简化为 sp->showAge();
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
输出:
1.2 重载 * 运算符
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
cout << "Person的有参构造调用" << endl;
this->m_Age = age;
}
void showAge()
{
cout << "年龄为: "<< this->m_Age << endl;
}
~Person()
{
cout << "Person的析构调用" << endl;
}
int m_Age;
};
class SmartPoint
{
public:
SmartPoint(Person * person)
{
this->m_person = person;
}
//重载 * 运算符
Person& operator*()
{
return *m_person;
}
~SmartPoint()
{
if (this->m_person)
{
delete this->m_person;
this->m_person = NULL;
}
}
private:
Person * m_person;
};
void test01()
{
//利用智能指针 管理 new出来的person的释放操作
SmartPoint sp(new Person(18));
(*sp).showAge();
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
输出:
二、分析与总结
在 C++ 中,我们可以重载 * 和 -> 运算符来实现自定义类型的解引用和成员访问操作。
* 运算符重载
:
*运算符可以被重载为类的成员函数或全局函数。
解引用运算符 * 的重载函数通常返回一个引用,以便对对象进行解引用操作。
在重载函数内部,可以实现自定义类型对象的解引用操作,返回解引用后的值。
重载的 * 运算符函数将在解引用操作时被调用。
-> 运算符重载
:
-> 运算符通常用于访问类的成员变量或成员函数。
-> 运算符的重载函数应该返回一个指向类对象的指针或一个类对象的引用。
在重载函数内部,可以实现对类对象的成员访问,并返回一个指向对象的指针或对象的引用。
重载的 -> 运算符函数将在使用箭头运算符时被调用。
使用 * 和 -> 运算符
:
通过重载 * 和 -> 运算符,我们可以使自定义类型的对象能够像指针一样进行解引用和成员访问。
使用 * 运算符可以对对象进行解引用操作,获取对象的值。
使用 -> 运算符可以访问对象的成员变量或成员函数。