c++ - 函数不显示返回值 - C++
问题描述
经过一番修改,我终于想出了一个函数,可以确定任何值的数据类型(在固定范围内)。
但是当我尝试从这个函数(char*
)打印出返回值时,什么都没有打印出来。
template <typename data> inline char* typeOf(data arg) {
const std::type_info& type = typeid(arg);
char* typeName;
if (type == typeid(bool)) strcpy(typeName, "boolean");
else if (
type == typeid(double) ||
type == typeid(float) ||
type == typeid(int) ||
type == typeid(long double) || type == typeid(long int) || type == typeid(long long) ||
type == typeid(signed int) || type == typeid(signed long int) || type == typeid(signed short int) ||
type == typeid(short int) ||
type == typeid(unsigned int) || type == typeid(unsigned long int) || type == typeid(unsigned short int)
) strcpy(typeName, "number");
else if (
type == typeid(char) ||
type == typeid(signed char) ||
type == typeid(std::string) ||
type == typeid(unsigned char) ||
type == typeid(wchar_t)
) strcpy(typeName, "string");
else if (type == typeid(void)) strcpy(typeName, "void");
else strcpy(typeName, "null");
// Expectation: Print out the value here
// Problem: It does not print anything!
std::cout << typeName << std::endl;
return typeName;
}
我确定这是我不熟悉的东西,但任何解释为什么没有打印出来的帮助std::cout
将不胜感激。目标是让一个函数确定一个值的数据类型并根据它返回一个字符串。
对此功能的任何改进也将不胜感激。
解决方案
Change char* typeName
to char* typeName=new char[50]
50 is just a number for example, is a dimension that can contains all the string you have written in your code. Note that strcpy(char* destination, const char* source) require that destination point to a location which size is greater than source so the destination can contains all the source. I suggest you to use the string for typeName and not char*. Remember that the pointer to char* you return need a delete somewhere in your code.
推荐阅读
- linux - 从 csv 文件中删除非 ascii 特殊字符
- apache-kafka-streams - 从ProcessorContext获取状态存储时是否可能出现InvalidStateStoreException?
- python - 使用元组键从字典创建 MultiIndex pandas DataFrame
- ruby-on-rails - Rails Docker 容器的 AWS 任务不断退出,服务器给出 503 错误
- java - 我应该为每个休息调用打开一个 JDBC 连接吗?
- r - 将数值转换为时间跨度格式
- android - 如何在recyclerview中设置每个cardview的位置?
- linear-regression - 即使使用预测()的 NA,如何进行预测?
- firebase - Firebase 托管:域已连接但无法正常工作
- ios - 将 UIView 层次结构呈现到图像所需的更快方法