C++ 引用

C++引用

// GCC 4.7.2

#include <iostream>
using namespace std;

class A
{
public:
    A (int number)
    : n(number)
    {}

public:
    int& n;
};

void func (int& a) {
    ++a;
}

int main () {

	// 引用不能直接定义
    // int& m = 0; // compile error
    cout << endl;

	// const常量可以定义为引用
    const int& m = 0;
    cout << m << endl; // 0
    cout << &m << endl; // 0x7ffffe25d08c
    cout << *&m << endl; // 0
    cout << endl;

    // 引用给引用赋值
    int x = 3, y=5;
    int& X = x;
    int& Y = y;
    X = Y;
    cout << X << endl; // 5
    cout << endl;

    // 引用的引用
    int c = 1;
    int& C = c;
    int& D = C;
    cout << D << endl; // 1
    D = 2;
    cout << c << endl; // 2
    cout << C << endl; // 2
    cout << endl;

    // 指向引用的指针
    int* p = &C;
    cout << *p << endl; // 2
    *p = 3;
    cout << *p << endl; // 3
    cout << C << endl; // 3
    cout << endl;

    // 引用作为成员变量
    int d = 5;
    A a(d);
    cout << a.n << endl; // 5
    a.n = 6;
    cout << a.n <<endl; // 6
    cout << d << endl; // 5
    cout << endl;

    // 引用大小为所引用对象在内存分配的大小
    double e = 1;
    double& E = e;
    cout << sizeof(E) << endl; // 8
    cout << endl;

    int* F = (int*) 8;
    // func (*F); // error, cannot access to memory 0x8
}

执行结果

0
0x7fff2cf54854
0

5

1
2
2

2
3
3

5
6
5

8
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值