所以我想用我的程序的一部分列表。我試圖熟悉圖書館列表,所以我寫了一個快速小程序來幫助我瞭解發生了什麼。這一切工作正常,但有一件事我不明白。返回類型的列表前(C++)
根據該: http://www.cplusplus.com/reference/list/list/front/ 用於前函數的返回類型應該是該類型的第一個元素(在此情況下,唯一元件)的一個參考(在這種情況下,房間)。
但我能夠訪問值而無需引用,因爲它似乎是所有的值直接傳遞(而不是引用)。這是預期的嗎?網站錯了嗎?我的編譯器錯了嗎(CodeBlocks 13.12)?
這裏是我的代碼:
#include <iostream>
#include <list>
using namespace std;
struct room {
int content;
struct room * north;
struct room * south;
struct room * east;
struct room * west;
} ;
int main()
{
list<room> mylist;
cout << (mylist.empty() ? "List is empty.\n" : "List is not empty.\n") << endl;
room * room1 = new room;
room1->content = 15;
cout
<< room1->content << "\n"
<< room1->north << "\n"
<< room1->south << "\n"
<< room1->east << "\n"
<< room1->west << "\n";
cout << "\n" << room1 << endl;
mylist.push_front(*room1);
cout << (mylist.empty() ? "\nList is empty.\n" : "\nList is not empty.\n") << endl;
delete room1;
room test_room = mylist.front();
cout
<< test_room.content << "\n"
<< test_room.north << "\n"
<< test_room.south << "\n"
<< test_room.east << "\n"
<< test_room.west << "\n";
cout << "\n" << &test_room << endl;
return 0;
}
嗯,是的,你只是複製前面的'房間'。這是你的問題嗎? – Barry
是的,我明白這一點。但根據網站,我不應該得到一個指針(類型房間)作爲函數_front_的返回值嗎?或者我誤解了單詞引用的定義? –
@MaxJacob,一個引用!=指針,在它上面讀到[here](/ questions/114180/pointer-vs-reference)和[here](/ questions/57483/what- a-pointer-variable-and-a-reference-variable-in) – WorldSEnder