开发者

What is the meaning of & in c++?

I want to know the meaning of & in the example below:

class1 &class1::instance开发者_开发技巧(){

///something to do

}


The & operator has three meanings in C++.

  • "Bitwise AND", e.g. 2 & 1 == 3
  • "Address-of", e.g.: int x = 3; int* ptr = &x;
  • Reference type modifier, e.g. int x = 3; int& ref = x;

Here you have a reference type modifier. Your function class1 &class1::instance() is a member function of type class1 called instance, that returns a reference-to-class1. You can see this more clearly if you write class1& class1::instance() (which is equivalent to your compiler).


This means your method returns a reference to a method1 object. A reference is just like a pointer in that it refers to the object rather than being a copy of it, but the difference with a pointer is that references:

  • can never be undefined / NULL
  • you can't do pointer arithmetic with them

So they are a sort of light, safer version of pointers.


Its a reference (not using pointer arithmetic to achieve it) to an object.


It returns a reference to an object of the type on which it was defined.


In the context of the statement it looks like it would be returning a reference to the class in which is was defined. I suspect in the "Do Stuff" section is a

return *this;


It means that the variable it is not the variable itself, but a reference to it. Therefore in case of its value change, you will see it straight away if you use a print statement to see it. Have a look on references and pointers to get a more detailed answer, but basecally it means a reference to the variable or object...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜