是否有任何无法获得地址的变量

Are there any variables whose address can not be obtained?

本文关键字:地址 变量 任何无 是否      更新时间:2023-10-16

我正在为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 可行的。它基本上包裹了一系列布尔。尽管如此,最终结果还是索引字节,而不是位。