注意:此为原创文章,未经同意,请勿随意转载。
1. 问题与思路
Q:实现一个与类型无关的比较函数
A:声明一个函数指针,每种类型各自实现自己的比较函数,函数指针指向具体类型的比较函数,即可实现类似模板的功能;
特别值得注意一点:函数指针中的形参类型得声明成void,这样任何类型都可以传递进来,也就是说,传给函数指针的参数是指向某种类型数据的指针,这样,入参类型就不受限制啦~*
升级版:其实还可以考虑模板,减少重复代码,见下一篇博客:《C和指针》——第13章函数指针的作用1:回调函数2(与模板结合,简化代码)
2. 具体实现
实现了int、char、string、类类型的比较函数。
#pragma once
#include <iostream>
#include <string>
using namespace std;
// 编写一个与类型无关的比较函数,注意不是模板,
// 方法:声明一个函数指针,每种类型各自实现自己的比较函数,函数指针指向具体类型的比较函数,即可实现类似模板的功能。
int(*compare)(const void*, const void*);
/*
约定具体类型的返回值代表含义,
返回0:相等;
返回-1:参数1<参数2
返回1:参数1>参数2;
*/
int compare_int(const void* a1, const void* a2)
{
if (*(int*)a1 < *(int*)a2)//先将void* 转换为int*; 然后再解引用*取指针所指地址中的值
{
return -1;
}
else if (*(int*)a1 == *(int*)a2)
{
return 0;
}
else
{
return 1;
}
}
int compare_char(const void* a1, const void* a2)
{
if (*(char*)a1 < *(char*)a2)
{
return -1;
}
else if (*(char*)a1 == *(char*)a2)
{
return 0;
}
else
{
return 1;
}
}
int compare_string(const void* a1, const void* a2)
{
if (*(string*)a1 < *(string*)a2)
{
return -1;
}
else if (*(string*)a1 == *(string*)a2)
{
return 0;
}
else
{
return 1;
}
}
int compare_Student(const void* a1, const void* a2);
class Student
{
public:
Student() :name(""), score(0) {}
Student(const string& _name, const int& _score) :name(_name), score(_score) {}
friend ostream& operator<<(ostream& os, const Student& stu)
{
os << stu.name << "\t" << stu.score;
return os;
}
friend int compare_Student(const void* a1, const void* a2)
{
if ((*(Student*)a1).score < (*(Student*)a2).score)
{
return -1;
}
else if ((*(Student*)a1).score == (*(Student*)a2).score)
{
return 0;
}
else
{
return 1;
}
}
private:
string name;
int score;
};
void TestFunctionPointer()
{
int a[] = { 4,2,5 };
char chars[] = "ascii";
string s[] = { "Anne","Zoe","Mary" };
Student stus[] = { {"Anne",80},{"Zoe",95},{"Mary",90} };
cout << "函数指针指向int型比较函数" << endl;
int nCountA = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < nCountA; ++i)
{
cout << a[i] << "\t";
}
cout << endl;
compare = compare_int;
int *pa = a;
while (pa != a + nCountA - 1)
{
cout << compare(pa++, pa) << endl;
}
cout << endl;
cout << "函数指针指向char型比较函数" << endl;
int nCountChar = sizeof(chars) / sizeof(chars[0]);
int nTmp = nCountChar - 1;
char *pc = &chars[0];
while (nTmp--)
{
cout << *pc++;
}
cout << endl;
compare = compare_char;
pc = &chars[0];
while (pc != &chars[nCountChar - 2])
{
cout << compare(pc++, pc) << endl;
}
cout << endl;
cout << "函数指针指向string型比较函数" << endl;
int nCountS = sizeof(s) / sizeof(s[0]);
for (int i = 0; i < nCountS; ++i)
{
cout << s[i] << endl;
}
compare = compare_string;
string *ps = &s[0];
while (ps != &s[nCountS - 1])
{
cout << compare(ps++, ps) << endl;
}
cout << endl;
cout << "函数指针指向类类型Student的比较函数" << endl;
int nCountStus = sizeof(stus) / sizeof(stus[0]);
for (int i = 0; i < nCountStus; ++i)
{
cout << stus[i] << endl;
}
compare = compare_Student;
Student *pStus = &stus[0];
while (pStus != &stus[nCountStus - 1])
{
cout << compare(pStus++, pStus) << endl;
}
}