给定以下代码:
#include <iostream>
using std::cout;
class A {
public:
virtual ~A() {}
int x,y,z;
};
int main (void)
{
std::cout<<&A::x;
std::cout<<&A::y;
std::cout<<&A::z;
}
输出是:
111
输出的含义是什么?为什么是1?是否有充分的理由通过指针访问类成员(没有创建对象)?
编辑 - 使用:
printf("%p",&A::x);
printf("%p",&A::y);
printf("%p",&A::z);
打印:4、8 和 C。
我想现在更有意义了..(字节) 但是,这样还有用吗?
最佳答案
没有operator<<(std::ostream&, T)
为 T = &C::m
定义.通常你会得到一个错误。
但是,T = bool
有一个。以及从成员指针到 bool
的隐式转换.所以你看到的输出只是那些指针不为空的结果(被转换为 true
)。
试试这个,例如:
#include <iomanip>
#include <iostream>
struct A
{
int x, y, z;
};
int main()
{
std::cout << std::boolalpha; // print boolean values as text
std::cout << &A::x << std::endl;
std::cout << &A::y << std::endl;
std::cout << &A::z << std::endl;
}
输出:
true
true
true
请注意,在代码 printf("%p", &A::X)
,你有未定义的行为。
%p
的值说明符必须是 void*
,并且没有从成员指针到 void*
的转换.相反,您对 void*
有别名(双关语) ,这是未定义的行为。 (想象一下 sizeof(&A::x)
是 4,而 sizeof(void*)
是 64;没有人说这不可能。)
您只需要接受并非所有指针都可以视为整数偏移量的想法。我们甚至可以打印一个指针是实现定义的:它可以为 null 打印“apple”,为一个值打印“pear”,如果(哑)实现想要打印另一个值,则为另一个“milk”。 I've touched on this difference between values and their representations before .
在这种情况下,值根本没有的输出。没关系,并非所有值都有有意义的打印输出。您最多可以打印出各个位:
#include <climits>
#include <iostream>
#include <type_traits>
template <typename T>
auto print_bits(const T& value)
-> typename std::enable_if<std::is_standard_layout<T>::value>::type
{
// it's okay to alias a standard-layout type as a sequence of bytes:
const auto valueAsBytes = reinterpret_cast<const unsigned char*>(&value);
for (std::size_t byte = 0; byte < sizeof(T); ++byte)
{
// print in reverse order
const std::size_t byteIndex = sizeof(T) - byte - 1;
const unsigned char byteValue = valueAsBytes[byteIndex];
for (std::size_t bit = 0; bit < CHAR_BIT; ++bit)
{
// print in reverse order
const std::size_t bitIndex = CHAR_BIT - bit - 1;
const bool bitValue = (byteValue & (1U << bitIndex)) != 0;
std::cout << (bitValue ? 1 : 0);
}
std::cout << ' ';
}
std::cout << std::endl;
}
(我以相反的顺序打印字节和位,因为在我的体系结构中,这会将最低有效位放在右侧。我更喜欢以这种方式查看二进制值。)
这给出了:
struct A
{
int x, y, z;
};
int main()
{
// example:
for (unsigned i = 0; i < 64; ++i)
print_bits(i);
std::cout << std::endl;
// member-pointers:
print_bits(&A::x);
print_bits(&A::y);
print_bits(&A::z);
}
输出:
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000001
00000000 00000000 00000000 00000010
[...]
00000000 00000000 00000000 00111101
00000000 00000000 00000000 00111110
00000000 00000000 00000000 0011111100000000 00000000 00000000 00000000
00000000 00000000 00000000 00000100
00000000 00000000 00000000 00001000
对于您所看到的成员指针,我们无法保证。
关于c++ - 为什么通过指针静态访问类数据成员返回1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16039854/