你好你好!
以下内容仅为当前认识,可能有不足之处,欢迎讨论!
文章目录
- 关系运算符-重载-判断相等
- 函数调用运算符重载
关系运算符-重载-判断相等
场景:两个对象,若有年龄和性别的不同,是否可以直接通过比较运算符来比较,而不用单独地取出每个对象的成员属性单独比较?
代码实现:
#include<iostream>
#include<string>
using namespace std;
void test_0215_1();
class Person {
friend void test_0215_1();
public:
Person(int age , string name);
~Person();
bool operator==(Person& contrast);
bool operator!=(Person& contrast);
private :
int person_age;
string person_name;
};
Person::Person(int age , string name) {
cout << "有参构造函数调用" << "." << endl;
person_age = age;
person_name = name;
cout << "age = " << age << "." << endl;
cout << "name = " << name << "." << endl;
}
Person::~Person() {
cout << "析构函数调用" << "." << endl;
}
bool Person::operator==(Person& contrast) {
int this_variable = this->person_age;
int person_variable = contrast.person_age;
string this_name = this->person_name;
string person_name = contrast.person_name;
if (this->person_age == contrast.person_age && this->person_name == contrast.person_name) {
return 1;
}
return 0;
}
bool Person::operator!=(Person& contrast) {
int this_age = person_age;
string this_name = person_name;
if (person_age != contrast.person_age && person_name != contrast.person_name) {
return 1;
}
return 0;
}
void test_0215_1() {
Person per(15 , "Tom"), son(15 , "Tom");
bool result = per == son;
cout << "per == son ?==>" << (per == son ) << "." << endl;
cout << "per != son ?==>" << (per != son) << "." << endl;
}
int main() {
cout << "hello ! world ! " << endl;
test_0215_1();
system("pause");
return 0;
}
运行结果:
可以看到,两者赋值都为"Tom15",经过重载后。信息一致。
函数调用运算符重载
使用场景:传入不同的参数,实现不同的功能;匿名类使用。
代码展示:
#include<iostream>
#include<string>
using namespace std;
void test_0215_2();
class Print {
public:
Print();
void operator()(string con);
private:
string print_context;
};
class Add {
public:
int operator()(int num, int ber) {
return num + ber;
}
};
void Print::operator()(string con) {
//第一个括号是重载的符号
cout << con << "." << endl;
}
Print::Print() {
//print_context = context;
}
void test_0215_2() {
//Print print();//这样写会被当成函数的声明,返回值是Print,应该下面这样写
Print print;
string query = "hello ? world ? ";
print(query);
cout << "正常使用add功能" << "." << endl;
int add = Add()(15, 20);
cout <<"add = Add(15,20) ==> " << add << endl;
cout << "匿名函数对象调用" << "." << endl;
cout <<"Add()(20,20) ==> " << Add()(20, 20) << "." << endl;
}
int main() {
cout << "hello ! world ! " << endl;
test_0215_2();
system("pause");
return 0;
}
运行结果
由图可以看出,打印输出有结果,同时有匿名函数对象的调用。
以上是我的学习笔记,希望对你有所帮助!
如有不当之处欢迎指出!谢谢!