是否有任何无法获得地址的变量
Are there any variables whose address can not be obtained?
我正在为CPP考试学习,其中一个问题将是这样:"如何获得可变地址,并且是否有任何无法获得地址的变量"?
所以第一个很容易,您只需使用"&"运算符,但是是否有任何变量(请注意,这个问题只涉及变量!(,无法使用Ampersand访问其地址?
任何帮助都将不胜感激
是否有无法获得地址的变量?
您无法获得位的构件变量的地址。
来自C 11标准:
操作员地址&不得将其应用于位场,因此没有指向位的指针。
在
我认为您的内容中的问题与标题的问题不同。我认为您的内容中的一个是您想要的。
有一些变量,其地址无法通过ampersand获得,因为您可以超载该操作员。
下面的代码,&a
不会给您a
的地址。
#include <iostream>
struct foo {
int operator &() {
return 900;
}
};
int main() {
foo a;
std::cout << (&a) << "n";
}
注意:该变量的地址可以通过其他方法获得。基本上,原理正在擦除类型,因此超载的操作员没有效果。std::addressof
实现了此功能。
,例如。您可以在C 中解决的最小内容是一个字节,因此尝试访问此bitField
中的1位uint8_t
中的任何一个都是不合法的。
#include <iostream>
#include <cstdint>
struct bitField {
uint8_t n0 : 1;
uint8_t n1 : 1;
uint8_t n2 : 1;
uint8_t n3 : 1;
uint8_t n4 : 1;
uint8_t n5 : 1;
uint8_t n6 : 1;
uint8_t n7 : 1;
};
int main() {
bitField example;
// Can address the whole struct
std::cout << &example << 'n'; // FINE, addresses a byte
// Can not address for example n4 directly
std::cout << &example.n4; // ERROR, Can not address a bit
// Printing it's value is fine though
std::cout << example.n4 << 'n'; // FINE, not getting address
return 0;
}
如Thedude在评论部分中提到的那样,STL具有std::bitset<N>
类,为此提供了A 可行的。它基本上包裹了一系列布尔。尽管如此,最终结果还是索引字节,而不是位。
相关文章:
- 将数组的地址分配给变量并删除
- 将地址分配给本地指针后,公共对象的变量将消失
- 通过按地址访问变量
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 为什么我可以将变量存储在不是其最小对齐方式的倍数的地址?
- 为什么同一个变量的内存地址不同?
- 从二进制流中读取时,将双精度变量的地址转换为 char* 意味着什么?
- 不同块作用域中的 C++ 变量具有相同的地址
- 循环中的变量被设置为下一个数组的元素始终具有相同的内存地址?
- C++在变量的内存地址上做什么来"deallocate"它?
- 如何在不为其声明变量的情况下获取和使用常量值的地址?
- 如何找到在本地范围内声明的变量的地址?
- 附加调试器并以编程方式获取变量地址 Visual Studio
- 初学者问题:C++指针/地址 - 和变量之后不是以前?
- 为什么我无法获取 MSVS2019 / C++ 中字符或uint8_t变量的内存地址?
- 为什么变量的打印地址在每次执行时都会打印随机值,即使它是 C 中的逻辑地址?
- 变量地址的运算符[]是如何工作的
- 使用基地址和偏移量获取变量的地址
- 两个不同的进程,在同一地址上有 2 个 std::atomic 变量?
- libmysql:警告:返回局部变量"行"的地址(C++/C)