函数不显示返回值 - C++

Function not displaying return value - C++

本文关键字:C++ 返回值 显示 函数      更新时间:2023-10-16

经过一番修补,我终于想出了一个函数来确定任何值的数据类型(在固定范围内(。

但是当我尝试打印出此函数的返回值(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打印任何东西将不胜感激。目标是让函数确定值的数据类型,并基于该数据类型返回字符串。

对此功能的任何改进也将不胜感激。

char* typeName更改为char* typeName=new char[50]例如,50只是一个数字,是一个可以包含您在代码中编写的所有字符串的维度。请注意,strcpy(char* destination, const char* source( 要求目标指向大小大于源的位置,以便目标可以包含所有源。我建议你使用类型名称的字符串而不是字符*。请记住,返回的指向 char* 的指针需要在代码中的某处删除。