An error about the Rvalue reference.

Source: Internet
Author: User



In the experiment class, some students encountered errors similar to the following code.

1. The following code compiles with an error.
#include <string>
using namespace Std;
Class complex{
Public
Complex (Float r = 0, float i = 0) {
Re = r;
im = i;
}
void print () {
cout<<re<< "+" <<im<<endl;
};
Private
float Re, im;
};
void F1 (Complex &c) {
C.print ();
}
Complex F2 () {
Complex C (1, 2);
return C;
}
int main () {
F1 (F2);
return 0;
}

Compilation result (MinGW):
|| = = = Build:debug in Test (compiler:gnu GCC compiler) ===|
e:\cpptest\test\main.cpp| | In function ' int main () ': |
E:\cpptest\test\main.cpp|25|error:invalid initialization of Non-const reference of type ' complex& ' from an rvalue of Type ' Complex (*) () ' |
E:\cpptest\test\main.cpp|17|error:in passing argument 1 of ' void F1 (complex&) ' |
|| = = = Build Failed:2 error (s), 0 warning (s) (0 minute (s), 0 second (s)) ===|

2. The error that appears is related to rvalue reference, you can find the answer by Baidu "right value reference".
Simply put, because the temporary variable is destroyed before it is given a new value, this rule prevents the value of the temporary variable from being modified.
The code changes to the following, and the compilation passes.
#include <iostream>
#include <iomanip>
#include <string>
using namespace Std;
Class complex{
Public
Complex (Float r = 0, float i = 0) {
Re = r;
im = i;
}
void print () const{//change to constant function
cout<<re<< "+" <<im<<endl;
};
Private
float Re, im;
};
void F1 (const Complex &c) {//change to regular reference
C.print ();
}
Complex F2 () {
Complex C (1, 2);
return C;
}
int main () {
F1 (F2 ());
return 0;
}

An error about the Rvalue reference.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.