C++函数重载例题

Descrption

Implement a template function cmp which compares any type of two elements.Makes it suitable to compare any two int, double, float, char, string and any two same type of pointers.*If the first parameter is equal to the second one, then return true, elsewise, false.

You can be careful that:

(1)When comparing two int, double, float, char*, string , you should compare their values.

(2)When comparing two pointers, you should compare the values they point to.

(3)the cmp function should always return a boolean value.

题目描述:

请实现一个模板函数cmp,它可以比较多种元素类型,包括int、double、float、char、string和任意两个相同类型的指针。

如果第一个参数等于第二个参数,则返回true, 否则返回 false。

注意:

比较int, double, float, char*, string 时,比较其值,比较指针变量时,比较其所指的值,cmd函数返回值为布尔类型。

已给出部分头文件和完整主函数,请补充头文件。


//cmp.h
template
bool cmp(const T a, const T b){
    if(a==b)
    {
    	return true;
	}
	else
	{
		return false;
	}
}
//main.cpp
#include 
#include 
#include "cmp.h"
using std::cout;
using std::endl;
using std::string;
int main() {
     int aInt = 1, bInt = 2;
     double aDouble = 3.0, bDouble = 3.0;
     char aChars[5] = "haha", bChars[5] = "hahb";
     char taChars[6] = "trick", tbChars[6] = "trick";
     string aStr = "haha", bStr = "aha";
     int* aIntPtr = &aInt, *bIntPtr = &bInt;
      cout << cmp(aInt, bInt)<< endl;
     cout << cmp(aDouble, bDouble)<< endl;
      cout << cmp(aChars, bChars)<< endl;
     cout << cmp(taChars, tbChars)<< endl;
     cout << cmp(aStr, bStr)<< endl;
     cout << cmp(aIntPtr, bIntPtr)<< endl;
     cout << cmp(&aDouble, &bDouble) << endl;
     return 0;
}
  

答案

//cmp.h
#include 
template
bool cmp(T a, T b) {
     if (a == b)
         return true;
     else
         return false;
}
 bool cmp(char* a, char* b) {
     if (strcmp(a, b) == 0)
         return true;
     else
         return false;
}
 template
bool cmp(T* a, T* b) {
     if (*a == *b)
         return true;
     else
         return false;
}
 

 

 

 

进入翻译页面

你可能感兴趣的:(C++)