gpt4 book ai didi

c++ - 我怎样才能得到三个字符数的总和?

转载 作者:行者123 更新时间:2023-11-30 04:13:53 25 4
gpt4 key购买 nike

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>

using namespace std;

template <class T>
T Summation(T a, T b, T c) {
return (a+b+c);
}

int main () {
char e = '5', f = '6', g = '7', h;
int a = 5, b = 6, c = 7, d;

h=Summation<char>(e,f,g);
cout << h << endl;
d=Summation<char>(a,b,c);
cout << d << endl;
}

我必须使用求和模板,并且我需要打印出 18 个与参数相同类型的模板。所以程序应该返回 18 作为 char 类型,然后下一行应该返回 18 作为 int 类型。

最佳答案

您可以对大多数类型使用通用模板,并为 char 添加特化:

template <class T>
T Summation(T a, T b, T c) {
return (a+b+c);
}

template <>
char Summation<char>(char a, char b, char c) {
return ((a - '0') + (b - '0') + (c - '0') );
}

用法(就像您在示例中所做的那样,编译器仅推断类型):

 char e = '5', f = '6', g = '7', h;
int a = 5, b = 6, c = 7, d;

h= Summation(e,f,g);
d= Summation(a,b,c);

关于c++ - 我怎样才能得到三个字符数的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19186624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com