用typeid().name()获取类型名

#include<iostream>
#include<typeinfo>//需要添加的头文件
using namespace std;
void main()
{
	//typeid().name()可以返回变量、函数、类的数据类型名,功能是相当强大的
	//注意:对非引用类型,typeid().name()是在编译时期识别的,只有引用类型才会在运行时识别

	const int a = 10;
	cout << typeid(&a).name() << endl;//const int *

	cout << typeid(typeid(a).name()).name() << endl;
	
	//结果为char const *,因此typeid().name()返回了存储类型名的字符串。
	
	//能否使用typeid().name()返回值作为类型名进行定义
	
	//typeid(a).name() b;//error!。这个想法其实很不错,我们在写代码的时候很可能需要设很多中间变量,如果不是自己写的代码,确定变量类型是很麻烦的。 
	
	//来解答下这个问题。用typeid().name()定义肯定是不行的,通过上面的返回结果就可以解释。返回的结果是cosnt char *,是一个地址。

}

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
我明白了,这是一个关于模板类的题目,需要实现一个类模板来进行分数的排序和平均值的计算。下面是我的实现,请你查看并测试一下。 ```cpp #include <iostream> #include <algorithm> #include <typeinfo> using namespace std; template<class T> class ScoreList { private: T *scores; int size; public: ScoreList(int maxsize = 20) : scores(new T[maxsize]), size(0) {} void sortScores() { sort(scores, scores + size, greater<T>()); } T averageScore() { if (size == 0) { return T(); } if (size < 3) { T sum = T(); for (int i = 0; i < size; ++i) { sum += scores[i]; } return sum / size; } sortScores(); T sum = T(); for (int i = 1; i < size - 1; ++i) { sum += scores[i]; } return sum / (size - 2); } void readScores() { cin >> size; for (int i = 0; i < size; ++i) { cin >> scores[i]; } } void printScores() { for (int i = 0; i < size; ++i) { cout << scores[i] << " "; } cout << endl; } void printAverageScore() { T avg = averageScore(); if (typeid(T).name() == typeid(int).name() || typeid(T).name() == typeid(double).name()) { cout << avg << endl; } else if (typeid(T).name() == typeid(char).name()) { cout << char(avg) << endl; } } ~ScoreList() { delete[] scores; } }; int main() { ScoreList<int> intScores; intScores.readScores(); intScores.sortScores(); intScores.printScores(); intScores.printAverageScore(); ScoreList<double> doubleScores; doubleScores.readScores(); doubleScores.sortScores(); doubleScores.printScores(); doubleScores.printAverageScore(); ScoreList<char> charScores; charScores.readScores(); charScores.sortScores(); charScores.printScores(); charScores.printAverageScore(); return 0; } ``` 输入格式如下: ``` 5 85 92 88 96 90 4 76.5 88.2 90.1 72.8 6 B C A A B C ``` 输出格式如下: ``` 96 92 90 88 85 89 90.1 88.2 76.5 72.8 82.15 C C B B A A 'B' ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值