首页 > 解决方案 > 函数不显示返回值 - 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将不胜感激。目标是让一个函数确定一个值的数据类型并根据它返回一个字符串。

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

标签: c++

解决方案


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.


推荐阅读