在C++中需要引用的是什么

Avi*_*ash 0 c++

今天有人问我这个问题.在C++中需要引用的是什么,为什么在C++中Bjarne Stroustrup考虑过reference.

Nic*_*tfm 5

这是Stroustrup的解释:http://www2.research.att.com/~bs/bs_faq2.html#pointers-and-references

C++继承了C的指针,因此我无法在不引起严重兼容性问题的情况下删除它们.引用对于几个方面很有用,但我在C++中引入它们的直接原因是支持运算符重载.

这是一个例子:

void f1(const complex* x, const complex* y) // without references
{
    complex z = *x+*y;  // ugly
    // ...
}

void f2(const complex& x, const complex& y) // with references
{
    complex z = x+y;    // better
    // ...
}   
Run Code Online (Sandbox Code Playgroud)