简体   繁体   English

&c ++中的含义是什么?

[英]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++. &运算符在C ++中有三个含义。

  • "Bitwise AND", eg 2 & 1 == 3 “按位与”,例如2 & 1 == 3
  • "Address-of", eg: int x = 3; int* ptr = &x; “Address-of”,例如: int x = 3; int* ptr = &x; int x = 3; int* ptr = &x;
  • Reference type modifier, eg int x = 3; int& ref = x; 参考类型修饰符,例如int x = 3; int& ref = x; 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 . 函数class1 &class1::instance()是类型为class1的成员函数,称为instance ,它返回一个引用 -to- class1 You can see this more clearly if you write class1& class1::instance() (which is equivalent to your compiler). 如果你编写class1& class1::instance() (它等同于你的编译器),你可以更清楚地看到这一点。

This means your method returns a reference to a method1 object. 这意味着您的方法返回对method1对象的引用 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 永远不会是undefined / NULL
  • you can't do pointer arithmetic with them 你不能用它们做指针运算

So they are a sort of light, safer version of pointers. 所以它们是一种轻巧,更安全的指针版本。

它是一个对象的引用(不使用指针算术来实现它)。

它返回对定义它的类型的对象的引用。

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 我怀疑在“Do Stuff”部分是一个

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. 因此,如果您更改了值,如果您使用print语句来查看它,您将立即看到它。 Have a look on references and pointers to get a more detailed answer, but basecally it means a reference to the variable or object... 看看引用和指针以获得更详细的答案,但基本上它意味着对变量或对象的引用......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM