个人学习记录:
1.关系运算符重载:
目的是直接实现p1 == p2的效果:如第一个代码框所示
(先创建两个对象)
Person p1(18,"张三");
Person p1(18,"李四");
if(p1 ==p2)//实现p1== p2
{
cout<<"相等"<<endl;
}
else
{
cout<<"不相等"<<endl;
}
//创建类
// 创建类
class Person
{
public:
// 构造函数,用于初始化对象的姓名和年龄
Person(string name, int age)
{
m_name = name;
m_age = age;
}
// 重载运算符函数,用于比较两个Person对象是否相等
bool operator==(Person &p)
{
// 检查两个对象的姓名和年龄是否相等
if (this->m_age == p.m_age && this->m_name == p.m_name)
{
return true; // 如果相等,返回true
}
else
{
return false; // 如果不相等,返回false
}
}
// 姓名成员变量
string m_name;
// 年龄成员变量
int m_age;
};
2.仿函数:
class Myprint
{
public:
//仿函数
// 重载函数调用运算符 (),使得对象可被当作函数调用
void operator()(string text)
{
cout<< text << endl;
}
};
//测试函数
void test()
{
Myprint myprint; // 创建 Myprint 类的对象 myprint
// 通过对象 myprint 调用重载的 () 运算符,将字符串作为参数传递
myprint("Hello World");
}
//主函数
int main()
{
test();
system("pause");
return 0;
}
结果:用反函数实现了print函数的效果
![](https://i-blog.csdnimg.cn/blog_migrate/8b6873eeebd1fd0fccb153b5a9c4e543.png)
学习至此,将开始我的C++ “继承” 之旅!祝我好运!
以上。2023年2月18日09:26:18