编程语言
首页 > 编程语言> > C++ 引用

C++ 引用

作者:互联网

10. 引用

char c;         // a character
char* p = &c;   // a pointer to a character
char& r = c;    // a reference to a character

10.1 引用详解

int X = 47;
int& Y = X;    // Y is a reference to X

// X and Y now refer to the same variable
cout << "Y = " << Y << endl;
Y = 18;
cout << "X = " << X << endl;

10.2 引用的规则

// In declaration
int x = 3;
int& y = x;
const int& z = x;

// As a function argument
void f(int& x);
f(y);       // initialized when function is called

10.3 示例

#include <iostream>
using namespace std;

int* f(int* x) {
    (*x)++;
    return x;
}

int& g(int& x) {
    x++;
    return x;
}

int x;
int& h() {
    int q;
    return x;
}

int main() {
    int a = 0;
    f(&a);  // Ugly (but explicit)
    cout << "f(&a) = " << a << endl;
    g(a);   // Clean (but hidden)
    cout << "g(a) = " << a << endl;
    h() = 16;
    cout << "h() = " << x << endl;
}

10.4 Pointers vs. References

// No references to references

// No pointers to references
    int&* p;        // illegal

// Reference to pointer is ok
    void f(int*& p);    // ok

// No arrays of references

参考链接:

标签:No,int,C++,existing,References,引用,references,pointer
来源: https://www.cnblogs.com/linkworld/p/16380775.html