在下面的例子中,test.cpp
:臨時打印地址?
#include <iostream>
using namespace std;
class Rectangle {
public:
int w, h;
Rectangle() : w(7), h(0) {} // constructor definition.
Rectangle(int x, int y) : w(x), h(y) {} // constructor definition.
};
class MyClass {
public:
Rectangle trec;
MyClass() {
}
Rectangle getRect() {
return trec;
}
};
int main() {
MyClass a = MyClass();
cout << &a.getRect() << endl;
}
...我gcc test.cpp -o test.exe
編譯時出現此錯誤:
test.cpp: In function ‘int main()’:
test.cpp:32:22: error: taking address of temporary [-fpermissive]
cout << &a.getRect() << endl;
我真的不明白什麼是暫時的在這裏 - a
被實例化時cout
運行,所以a.trec
也應該實例化,並有一個地址,這正是getRect()
返回? (或不復製得到隱含在return
創建的,因爲返回類型被定義爲Rectangle
,而不是Rectangle*
?)
在任何情況下,我想檢查原來這樣寫的代碼,並在a.trec
是private
,所以getRect()
是我可以在我的代碼中使用的唯一東西 - 任何機會在這種情況下打印a.trec
的地址?
一個'Rectangle'是暫時的。 – PSkocik