【问题标题】:The address of character type variable字符类型变量的地址
【发布时间】:2013-11-17 16:02:34
【问题描述】:

这里只是一个测试原型:

#include <iostream>
#include <string>
using namespace std;

int main()
{
   int a=10;
   char b='H';
   string c="Hamza";

   cout<<"The value of a is : "<<a<<endl;
   cout<<"The value of b is : "<<b<<endl;
   cout<<"The value of c is : "<<c<<endl<<endl;

   cout<<"address of a : "<<&a<<endl;
   cout<<"address of b : "<<&b<<endl;
   cout<<"address of c : "<<&c<<endl;

   return 0;
}

为什么变量'b'的地址,是字符类型,不打印?

【问题讨论】:

    标签: c++ character memory-address


    【解决方案1】:

    &lt;&lt; 有一个重载,它接受一个指向 char 的指针并将其解释为终止的 C 样式字符串。将其用于任何其他 char 的地址将大错特错。

    相反,转换为无类型指针,这样&lt;&lt; 就不会变得太聪明:

    cout << static_cast<void*>(&b)
    

    【讨论】:

    • 谢谢,但谁能给我一个链接来解释
    • @HamzaUmar:有此重载herehere 的引用。 C++11 27.7.3.6.4 是权威参考。你的介绍书应该描述void*的用途。
    【解决方案2】:

    表达式 &b 的类型为 char *。当运算符

    ( void * ) &b
    

    reinterpret_cast<void *>( &b )
    

    【讨论】:

      【解决方案3】:

      代码中的 &lt;&lt; 运算符在 C++ 11 中被重载。它不会与任何其他类型(如 intstring)冲突,但它需要指向 char 的指针,如果使用它会产生不希望的结果。

      你可以这样做:-

      cout << static_cast<void*>(&b)
      

      【讨论】:

        猜你喜欢
        • 2021-03-01
        • 1970-01-01
        • 2020-01-07
        • 2011-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-24
        • 1970-01-01
        相关资源
        最近更新 更多