问题描述
以下是我的C ++文本的摘录,阐明了使用复制构造函数声明类的语法.
The following is an excerpt from my C++ text, illustrating the syntax for declaring a class with a copy constructor.
class Student {
int no;
char* grade;
public:
Student();
Student(int, const char*);
Student(const Student&);
~Student();
void display() const;
};
复制构造函数,如下所示:
The copy constructor, as shown here:
Student(const Student&);
在参数Student后面有一个&符号.
Has an ampersand after the parameter Student.
在C和C ++中,我相信,&字符用作指针的地址"运算符.当然,使用&指针名称之前的字符之前,复制构造函数在其后使用它,因此我认为这是不同的运算符.
In C, and C++ as-well I believe, the ampersand character is used as a 'address of' operator for pointers. Of course, it is standard to use the & character before the pointer name, and the copy constructor uses it after, so I assume this is not the same operator.
我发现的&字符的另一种用法与Rvalues和Lvalues有关,如下所示: http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
Another use of the ampersand character I found, relates to Rvalues and Lvalues as seen here: http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
我的问题不是关于右值和左值,我只是想知道为什么&字符放置在 参数之后,该参数的名称以及是否/为什么必要.
My question is not about Rvalues and Lvalues, I just want to know why the & character is placed after parameter, and what this is called and if/why it is necessary.
推荐答案
C ++具有C中不存在的引用类型.&
用于定义这种类型.
C++ has reference type that does not exist in C. &
is used to define such a type.
int i = 10;
int& iref = i;
此处iref
是对i
的引用.
对i
所做的任何更改都可以通过iref
看到,而对iref
所做的任何更改都可以通过i
看到.
Any changes made to i
is visible through iref
and any changes made to iref
is visible through i
.
iref = 10; // Same as i = 10;
i = 20; // Same as iref = 20;
引用可以是左值引用或右值引用.在上面的示例中,iref
是左值引用.
The reference can be an lvalue reference or an rvalue reference. In the above example, iref
is an lvalue reference.
int&& rref = 10;
此处rref
是右值引用.
您可以在 http://en.cppreference.com上了解有关右值引用的更多信息./w/cpp/language/reference .
这篇关于C ++复制构造函数语法:和符号是否引用r/l值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!