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

时间:2018-02-08 18:49:07

标签: c++

我正在学习CPP考试,其中一个问题是:“如何获取变量地址,是否有任何无法获得地址的变量”?

所以第一个很简单,你只需要使用“&”运算符,但是有没有变量(请注意,这个问题仅涉及变量!),其地址无法用&符号访问?

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:10)

  

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

您无法获取作为位字段的结构的成员变量的地址。

来自the C++11 Standard

  

运营商地址&不应用于位域,因此没有指向位域的指针。

答案 1 :(得分:5)

  

但是有没有变量(请注意,这个问题只涉及变量!),其地址无法用&符号访问?

我认为您的内容中的问题与标题中的问题不同。我假设你的内容中的那个是你想要的。

有些变量的地址无法通过&符号获得,因为您可以重载该运算符。

以下代码<div> <img class="image" src="http://via.placeholder.com/150x150"> <div class="circle"></div> </div>不会为您提供&a的地址。

a

注意:此类变量的地址可以通过其他方法获得。基本上,原则是擦除类型,以便重载操作符没有效果。 #include <iostream> struct foo { int operator &() { return 900; } }; int main() { foo a; std::cout << (&a) << "\n"; } 实现了此功能。

答案 2 :(得分:3)

以此为例。你可以在C ++中解决的最小问题是一个字节,因此试图访问uint8_t中的任何1位bitField是不合法的。

#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>,为此提供解决方法。它基本上包含了一系列bool。最后,结果是索引字节,而不是位。

相关问题