冰焰123 2016-02-14 01:01 采纳率: 100%
浏览 1596
已采纳

C++返回局部引用的问题

我是新手,向各位大神请教一个问题:
用元素接收返回的局部引用,会出现内存错误,但用引用接收返回的局部引用,没有问题,是什么原因?谢谢各位大神解答

  • 写回答

10条回答 默认 最新

  • threenewbee 2016-02-14 01:37
    关注

    因为你定义了拷贝构造函数

     #include <stdio.h>
    #include <iostream>
    using namespace std;
    
    class Teacher
    {
    public:
        Teacher(int a);
        Teacher(const Teacher &t2);
        Teacher& retT();
        Teacher(int a,int b);
        ~Teacher();
        int a;
        int b;
    };
    
    Teacher::Teacher(int a) {
    this->a = a;
    cout << "执行Teacher构造函数 \n a=" << this->a << endl;
    }
    Teacher::Teacher(int a,int b) {
    this->a = a;
    this->b = b;
    cout << "执行Teacher构造函数 \n this->a=" << this->a << ";this->b=" << this->b<< endl;
    }
    Teacher::Teacher(const Teacher &t2) {
    this->a = t2.a;
    cout << "执行Teacher的copy函数 t2.a=" << t2.a << endl;
    }
    Teacher::~Teacher() {
    cout << "执行Teacher析构函数 this->=" << this->a << endl;
    }
    
    Teacher& Teacher::retT() {
    Teacher t1(120);
    Teacher &t2 = t1;
    return t2;
    }
    void main() {
    Teacher t1(12);
    Teacher &t2 = t1.retT();
    //Teacher t2 = t1.retT();
    cout << "main05中的t2.a=" << t2.a << endl;
    }
    

    这么写不会调用拷贝构造函数

    执行Teacher构造函数
    a=12
    执行Teacher构造函数
    a=120
    执行Teacher析构函数 this->=120
    main05中的t2.a=120
    执行Teacher析构函数 this->=12
    Press any key to continue

    这是输出

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题