C ++将指针传递给期望void *的函数的方式有两种,为什么?

时间:2018-08-25 11:15:07

标签: c++ function void void-pointers

最近我偶然发现了融合到此示例中的代码:

void PrintThis (void* input)
{
    std::cout << input << std::endl;
    std::cout << (char*)input << std::endl;
}

int main(void)
{
    char question[] = "Why does it work?";
    PrintThis(question);    // output: address + 'Why does it work?' - expected!
    PrintThis(&question);   // output: address + 'Why does it work?' - unexpected
    char* thisIsDiff = "This is different";
    PrintThis(thisIsDiff);    // output: address + 'This is different' - expected
    PrintThis(&thisIsDiff);   // output: address + rubbish - expected
    return 0;
}

请注意标有意外的行。为什么输出与上面的行相同?为什么当函数参数为char *而不是void时,为什么甚至不编译?

0 个答案:

没有答案