C++ copy constructor syntax: Is ampersand reference to r/l values?

浪尽此生 提交于 2019-12-13 09:04:24

问题


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&);

Has an ampersand after the parameter Student.

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.

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.


回答1:


C++ has reference type that does not exist in C. & is used to define such a type.

int i = 10;
int& iref = i;

Here iref is a reference to 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;

The reference can be an lvalue reference or an rvalue reference. In the above example, iref is an lvalue reference.

int&& rref = 10;

Here rref is an rvalue reference.

You can read more about rvalue references at http://en.cppreference.com/w/cpp/language/reference.



来源:https://stackoverflow.com/questions/33290801/c-copy-constructor-syntax-is-ampersand-reference-to-r-l-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!