我是新手,向各位大神請教一個問題:
用元素接收返回的局部引用,會出現內存錯誤,但用引用接收返回的局部引用,沒有問題,是什麼原因?謝謝各位大神解答
因為你定義了拷貝構造函數
#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
這是輸出