关于右值引用的一个错误。
来源:互联网 发布:淘宝客服骂人投诉电话 编辑:程序博客网 时间:2024/05/22 17:36
实验课上,有同学遇到类似如下代码的错误。
1. 如下代码编译时会出错。
#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;
}
编译结果(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. 出现的错误与右值引用有关系,可以百度“右值引用”,可找到答案。
简单讲,由于临时变量在被赋予新值之前,都会被销毁,此规则可防止修改临时变量的值。
代码改为如下后,编译通过。
#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{ //改为常函数
cout<<re<<"+"<<im<<endl;
};
private:
float re, im;
};
void f1(const Complex &c){ //改为常引用
c.print();
}
Complex f2(){
Complex c(1, 2);
return c;
}
int main(){
f1(f2());
return 0;
}
- 关于右值引用的一个错误。
- 关于右值引用的粗略研究
- 关于int &&的使用---右值引用
- 关于右值引用的粗略研究
- 关于C++的右值、const引用、右值引用、const成员函数及相关扩展
- 一个关于VB工程引用的错误!
- 左值和右值引用的一个例子
- C++的右值引用
- c++的右值引用
- 关于std::move与右值引用
- 深刻理解引用、const引用、右值引用的本质
- C++0x的右值和右值引用
- C++0x的右值和右值引用
- 返回一个临时变量的右值引用,那么临时对象什么时候释放?
- 无聊的细节:指针、引用、右值
- C++ 11 右值引用的理解
- C++ 11右值引用的理解
- C++ 11的右值引用
- MotionEvent子类注释
- 第八周项目一(1):实现复数类中的运算符重载:类的成员函数
- iOS 实现倒计时
- 从零开始nodejs系列文章
- perl 编程基础
- 关于右值引用的一个错误。
- 银联在线支付---利用测试案例代码模拟支付应用(修改)
- 读取excel 工具类
- Android f_rndis 分析笔记
- RFID系统二进制树型搜索算法是如何解决碰撞的?简述其实现步骤
- 散列(2)线性探测法和双重散列法
- Qt for Android - ANT_HOME is set incorrectly or ant could not be located
- Wireless Network(POJ-2236)(并查集)
- 第2章 8