C++ 为什么`(void*)&;`获取变量的地址?

C++ 为什么`(void*)&;`获取变量的地址?,c++,casting,operator-overloading,c-strings,void-pointers,C++,Casting,Operator Overloading,C Strings,Void Pointers,有人能解释一下这背后的逻辑吗?为什么无效?比如说 #include <iostream> using namespace std; int main() { char c; cout << (void *)&c; return 0; } #包括 使用名称空间std; int main() { 字符c; coutcout 为什么(void*)和获取变量的地址 一元&是addressof运算符。addressof运算符获取操作数的地址,因为这

有人能解释一下这背后的逻辑吗?为什么
无效
?比如说

#include <iostream>
using namespace std;
int main()
{
    char c;
    cout << (void *)&c;
    return 0;
}
#包括
使用名称空间std;
int main()
{
字符c;
cout
cout
为什么
(void*)和
获取变量的地址

一元
&
是addressof运算符。addressof运算符获取操作数的地址,因为这是该运算符的用途

为什么无效

因为

  • &c
    的类型是
    char*
    ,输出流将该类型的指针视为指向以null结尾的字符串的指针,处理方式与所有其他指针不同。具体而言,字符串的内容将被输出。插入一个不是指向null终端的指针的
    char*
    将未定义的字符串插入字符流将导致未定义的行为。
    &c
    不是指向以null结尾的字符串的指针。将另一种类型的指针插入字符流将导致输出地址的数字表示形式

    该示例将
    &c
    转换为另一种指针类型,这样它就不会被视为以null结尾的字符串

  • 所有对象指针都可以转换为
    void*
    ,因此这是通常选择用于输出字符地址的指针类型


  • 更详细地说,字符流插入运算符具有重载:

    operator<<(ostrea&, const char*);
    operator<<(ostrea&, const void*); // I'm cheating a bit
                                      // this is technically a member overload
    

    运算符当且仅当变量为NULL时,我需要将其转换为
    void*
    吗?@否。仅当您要打印
    字符的地址时,即
    字符*
    常量字符*
    operator<<(ostrea&, const char*);
    operator<<(ostrea&, const void*); // I'm cheating a bit
                                      // this is technically a member overload
    
    #include <iostream>
    
    int main() 
    {
        const char *s = "Hello";
        
        std::cout << s << '\n';
        std::cout << static_cast<const void *>( s ) << '\n';
        
        return 0;
    }
    
    Hello
    0x5598fd4a3004