What does '&' do in a C++ declaration?

前端 未结 7 1373
后悔当初
后悔当初 2020-11-28 03:40

I am a C guy and I\'m trying to understand some C++ code. I have the following function declaration:

int foo(const string &myname) {
  cout << \"ca         


        
7条回答
  •  Happy的楠姐
    2020-11-28 04:32

    One way to look at the & (reference) operator in c++ is that is merely a syntactic sugar to a pointer. For example, the following are roughly equivalent:

    void foo(int &x)
    {
        x = x + 1;
    }
    
    void foo(int *x)
    {
        *x = *x + 1;
    }
    

    The more useful is when you're dealing with a class, so that your methods turn from x->bar() to x.bar().

    The reason I said roughly is that using references imposes additional compile-time restrictions on what you can do with the reference, in order to protect you from some of the problems caused when dealing with pointers. For instance, you can't accidentally change the pointer, or use the pointer in any way other than to reference the singular object you've been passed.

提交回复
热议问题