gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:27:44 26 4
gpt4 key购买 nike

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

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com