search

Home  >  Q&A  >  body text

c++中成员变量为引用

class A {
private:
    int&a;
public:
    A(int b):a(b){}
    void showaddress() {
        cout<<"address: "<<&a<<endl;
    }
    void setvalue() {
        a = 3;
    }
    void show() {
        cout<<a<<endl;
    }
};

int main(void) {
    int b = 1;
    A*a = new A(b);
    a->showaddress();
    a->setvalue();
    a->show();
    return 0;
}

问题:
在初始化类A中的成员变量int&a时,用的是一个临时变量。在离开A构造函数后,这个临时变量已经释放,为什么之后的a->showaddressa->setvalue依然可以正常调用?

迷茫迷茫2803 days ago707

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:00:36

    The b passed to the constructor is indeed a temporary variable, it might as well be called b'. However, b' also has a location in memory. Although the life cycle of b' is over, its mission has been completed - let a "point" to the memory address where b' is located (that is, the return value of the function showaddress), or in other words, to where b' is (or where it once was). memory location) has a new name a. Therefore, the "life" of b' is "continued" through a. . . This memory may not have been reallocated yet (according to the principle of locality of the program, it is generally not allocated immediately), and you can scribble in it (for example, calling the function setvalue).

    reply
    0
  • Cancelreply