C++中&的含义是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5289572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the meaning of & in c++?
提问by Milad Sobhkhiz
I want to know the meaning of & in the example below:
我想知道下面例子中 & 的含义:
class1 &class1::instance(){
///something to do
}
回答by Lightness Races in Orbit
The &
operator has three meanings in C++.
该&
运营商在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;
- “按位与”,例如
2 & 1 == 3
- “地址”,例如:
int x = 3; int* ptr = &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
. You can see this more clearlyif you write class1& class1::instance()
(which is equivalent to your compiler).
这里有一个引用类型修饰符。您的函数class1 &class1::instance()
是一个class1
名为的成员函数instance
,它返回一个引用-to- class1
。如果您编写(相当于您的编译器),您可以更清楚地看到这一点class1& class1::instance()
。
回答by Wim
This means your method returns a referenceto 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:
这意味着您的方法返回对 method1 对象的引用。引用就像一个指针,因为它引用对象而不是它的副本,但与指针的区别在于引用:
- can never be undefined / NULL
- you can't do pointer arithmetic with them
- 永远不能是未定义的 / NULL
- 你不能用它们做指针运算
So they are a sort of light, safer version of pointers.
所以它们是一种轻量级、更安全的指针版本。
回答by stefan
Its a reference (not using pointer arithmetic to achieve it) to an object.
它是一个对象的引用(不使用指针算法来实现它)。
回答by Puppy
It returns a reference to an object of the type on which it was defined.
它返回对定义它的类型的对象的引用。
回答by Thomas Jones-Low
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;
回答by learnerNo1
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...
这意味着变量不是变量本身,而是对它的引用。因此,如果它的值发生变化,如果您使用打印语句查看它,您将立即看到它。查看引用和指针以获得更详细的答案,但基本上它意味着对变量或对象的引用......