引用作为类的成员

#include <iostream>
#include <stdio.h>

using std::cout;
using std::endl;

class A{
public:
    A(int a):r(a){printf("A::r %p\n", &r);}
    int & r;
};

int main()
{
    cout << sizeof(A)<<endl;
    int a = 0;
    printf("outer a %p\n", &a);
    A b(a);
    return 0;
}

首先,sizeof(A)是8(64位系统),因为引用底层是用指针实现的。

其次,A的构造函数是有bug的。因为A.r引用的是形参。这个形参在构造函数调用的栈上,构造函数结束后立马销毁。

正确版本:

A(const int &a):r(a){}

猜你喜欢

转载自www.cnblogs.com/buddho/p/11865276.html
今日推荐