我想知道那个Array不用Array&的时候返回的*this返回的不是arr1是返回谁的
Array Array::peitrisof() { return *this; }
Array Array::peitrisof() { return *this; }
2019-01-21
补上楼:
#include <iostream> using namespace std; class Test { public: Test test1() { return *this; } int i; }; int main() { Test test; Test test2 = test.test1(); cout << "test p = " << &test << "*this p = " << &(test2) << endl; return 0; }
输出为:test p = 0x7ffffb4c9b20 *this p = 0x7ffffb4c9b24
可以看到是地址不同的两个Test 实例。
若直接将:
cout << "test p = " << &test << "*this p = " << &(test2) << endl; //修改为以下代码: cout << "test p = " << &test << "*this p = " << &(test.test1()) << endl; //则编译会报 test.cpp:16:67: error: taking address of temporary [-fpermissive] 错,即 //引用返回的临时变量地址而引起的编译性错误
举报