c++ - 指向成员的指针 : what does the pointer value represent?

标签 c++ pointers

我正在玩指向成员的指针,并决定实际打印指针的值。结果出乎我的意料。

#include <iostream>

struct ManyIntegers {

    int a,b,c,d;
};

int main () {

    int ManyIntegers::* p;

    p = &ManyIntegers::a;
    std::cout << "p = &ManyIntegers::a = " << p << std::endl; // prints 1

    p = &ManyIntegers::b;
    std::cout << "p = &ManyIntegers::b = " << p << std::endl; // prints 1

    p = &ManyIntegers::c;
    std::cout << "p = &ManyIntegers::c = " << p << std::endl; // prints 1

    p = &ManyIntegers::d;
    std::cout << "p = &ManyIntegers::d = " << p << std::endl; // prints 1

    return 0;
}

为什么p的值总是1? p 的值不应该以某种方式反射(reflect)它指向哪个类成员吗?

最佳答案

正如所有人所说,ostream没有合适的 operator<<定义。

试试这个:

#include <cstddef>
#include <iostream>

struct Dumper {
  unsigned char *p;
  std::size_t size;
  template<class T>
  Dumper(const T& t) : p((unsigned char*)&t), size(sizeof t) { }
  friend std::ostream& operator<<(std::ostream& os, const Dumper& d) {
    for(std::size_t i = 0; i < d.size; i++) {
      os << "0x" << std::hex << (unsigned int)d.p[i] << " ";
    }
    return os;
  }
};

#include <iostream>

struct ManyIntegers {

    int a,b,c,d;
};

int main () {

    int ManyIntegers::* p;

    p = &ManyIntegers::a;
    std::cout << "p = &ManyIntegers::a = " << Dumper(p) << "\n"; 

    p = &ManyIntegers::b;
    std::cout << "p = &ManyIntegers::b = " << Dumper(p) << "\n"; 

    p = &ManyIntegers::c;
    std::cout << "p = &ManyIntegers::c = " << Dumper(p) << "\n"; 

    p = &ManyIntegers::d;
    std::cout << "p = &ManyIntegers::d = " << Dumper(p) << "\n"; 

    return 0;
}

关于c++ - 指向成员的指针 : what does the pointer value represent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12110416/

相关文章:

c++ - 为什么我得到 QUnhandledException?

c++ - 无重复数的随机数生成器

c - 链接列表错误 "Segmentation Fault"Core Dumped

c - 如何打印指针的指向值?

c++ - 将字符串转换为 const char *

C++ stringstream 函数没有正确返回

c++ - 以最快的方式获取像素颜色?

c++ - 测量的 fps 高于理论值

C++ 和 Lua : automatically register functions

c++ - 确保在 C++ 编译时正确的双指针传递方法