c++ - "friend std::ostream& operator<<(std::ostream& out, LinkedList& list)"是什么意思?

标签 c++ linker-errors friend

因此,我得到了一个带有起始代码的任务来实现一个链表(我已经成功地完成了一个未排序的双向链表)并且在给定头文件的起始代码中有一个友元声明似乎有允许我使用 cout 打印链表的目标陈述。这是头文件;请注意,我在私有(private)部分写了所有内容。

#ifndef _LINKED_LIST_
#define _LINKED_LIST_

#include <ostream>

class LinkedList
{
public:
    LinkedList();
    ~LinkedList();

    void add(char ch);
    bool find(char ch);
    bool del(char ch);

    friend std::ostream& operator<<(std::ostream& out, LinkedList& list);

private:
    struct node
    {
        char data;
        node * next;
        node * prev;
    };
    node * head, * tail;
};

#endif // _LINKED_LIST_

main ,这也是起始代码的一部分,老师写了cout << list;这让我相信头文件中的 friend 语句的目标是允许列表轻松地打印到控制台。通常我不会在意,但如果我不注释掉 cout << list;声明然后链接器为我提供以下错误 cout << list; 的每个实例

app.o: In function 'main':
[code directory]/app.cpp:[line the statement is on]: undefined reference to
'operator<<(std::ostream&, LinkedList&)'

我的问题是friend std::ostream& operator<<(std::ostream& out, LinkedList& list) 是什么意思? cout << list; 的意思和原因导致这个错误?代码在没有语句的情况下执行良好,并且由于我使用教师的 makefile 来组装作业,我认为这不是问题所在。

app.cpp如下

#include <iostream>
#include "linkedlist.h"

using namespace std;

void find(LinkedList& list, char ch)
{
    if (list.find(ch))
        cout << "found ";
    else
        cout << "did not find ";
    cout << ch << endl;
}

int main()
{
    LinkedList  list;

    list.add('x');
    list.add('y');
    list.add('z');
    cout << list;
    find(list, 'y');

    list.del('y');
    cout << list;
    find(list, 'y');

    list.del('x');
    cout << list;
    find(list, 'y');

    list.del('z');
    cout << list;
    find(list, 'y');

    return 0;
}

最佳答案

what does friend std::ostream& operator<<(std::ostream& out, LinkedList& list) mean

friend declaration声明一个非成员函数,并使其成为该类的友元,这意味着它可以访问 privateprotected类(class)成员LinkedList .

and why does cout << list; cause this error?

由于只是声明,所以需要自己定义。这就是您收到 undefined reference 链接器错误的原因。

您可以在类中定义它(并内联定义)

class LinkedList
{
    ...
    friend std::ostream& operator<<(std::ostream& out, LinkedList& list) {
        // output something
        return out;
    }
    ...
};

或者在类外定义:

std::ostream& operator<<(std::ostream& out, LinkedList& list) {
    // output something
    return out;
}

顺便说一句:我建议你将第二个参数设为 const LinkedList& ;它不应在 operator<< 内修改.

关于c++ - "friend std::ostream& operator<<(std::ostream& out, LinkedList& list)"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38093045/

相关文章:

c++ - 如何组织包含模板和 friend 混合的类?

c++ - 创建行为类似于 stringstream 的类的最简单方法

c++ - QListWidget::itemChanged 信号在 qt 中触发了两次

c++ - 好友功能问题

c++ - 构建 64 位 dll 时为 "File contains invalid .pdata contributions"

c++ - 在 MSVC++2010 中使用静态链接在调试配置中编译 DLL 时出现链接器错误

c++ - C++ 中的 friend 成员函数 - 前向声明不起作用

c++ - 连续内存块中的位计数

C++在传递给类时删除指向指针的指针

c++ - gfortran undefined reference