C++ 列表前面的返回类型(C+;+;)
所以我想在我的程序中使用一个列表。我正试图了解图书馆的列表,所以我写了一个快速的小程序来帮助自己理解正在发生的事情。一切正常,但有一件事我不明白 据此: front函数的返回类型应该是第一个元素(本例中的唯一元素)的类型(在本例中为room)的引用 但是我能够访问这些值而不必引用,因为似乎所有的值都是直接传递的(不是通过引用)。这是预期的吗?网站错了吗?我的编译器错了吗(代码块13.12) 这是我的密码:C++ 列表前面的返回类型(C+;+;),c++,function,reference,linked-list,return-type,C++,Function,Reference,Linked List,Return Type,所以我想在我的程序中使用一个列表。我正试图了解图书馆的列表,所以我写了一个快速的小程序来帮助自己理解正在发生的事情。一切正常,但有一件事我不明白 据此: front函数的返回类型应该是第一个元素(本例中的唯一元素)的类型(在本例中为room)的引用 但是我能够访问这些值而不必引用,因为似乎所有的值都是直接传递的(不是通过引用)。这是预期的吗?网站错了吗?我的编译器错了吗(代码块13.12) 这是我的密码: #include <iostream> #include <list&g
#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;
}
#包括
#包括
使用名称空间std;
结构室{
智力内容;
结构室*北面;
建筑房*南;
结构室*东;
结构室*西;
} ;
int main()
{
列出我的清单;
cout有两种类型的构造函数自动添加到您声明的任何类中:默认构造函数,默认初始化该类的所有成员§12.1.4
,以及复制构造函数§12.8.7
在您的情况下,我们必须查看复制构造函数:
复制构造函数的声明如下所示(如果您特别将其写下§12.8.8
):
如您所见,它将常量
引用到另一个文件室
,并通过从传入的文件室
复制来初始化自身的所有值
发生的第一件事是,列表添加了传递到mylist.push_front(*room1)
中的文件室的副本(您可以看到push_front()
通过const ref§23.3.5.4
获取元素,但在内部复制它们。为此,第一次调用复制构造函数
稍后使用mylist.front()
访问元素时,它返回一个引用,但因为您初始化了room
的值,而不是引用-room test\u room=mylist.front()
-第二次调用复制构造函数。要通过引用正确捕获列表的前面,您需要执行room&test\u room=mylist.front();
<> >注释:所有的代码>〈NBR < /C> >参考C++标准中的相应部分。嗯,是的,你只是复制前面的代码>房间< /代码>。这是你的问题吗?是的,我理解。但是,根据网站,我不应该得到一个指针(房间类型)吗?作为函数front的返回值?还是我误解了单词reference的定义?@MaxJacob,一个reference!=指针,请仔细阅读并感谢您的澄清。这应该会有很大帮助!为什么不是这样?:room*test\u room=mylist.front()
查看我在上面发布的链接或。欢迎来到stackexchange BTW感谢你们两位的帮助!默认构造函数默认初始化其成员,而不是零初始化它们。push_front()
通过引用常量而不是值来获取其参数。感谢@Barry,在标准、固定和添加的段落中查找了它
struct room{
room(const room&); // Copy-Ctor, implicitly added by the compiler
};