首页 > 解决方案 > 为什么在这种情况下覆盖流插入运算符时会出现“未找到运算符”错误?

问题描述

我有一个包含多个头文件和源文件的项目,我已将其缩短为我认为在这里很重要的内容(尽管我可能是错的)。它们看起来像这样:

A.hpp:

#pragma once
struct date_t {
    unsigned int day{ 0 };
    unsigned int month{ 0 };
    unsigned int year{ 0 };
};

A.cpp:

#include <iostream>
#include "A.hpp"
using namespace std;
ostream& operator<<(ostream& output, const date_t& date) {
    output << date.month << "/" << date.day << "/" << date.year;
    return output;
}

B.hpp:

#pragma once
#include "A.hpp"
class B {
public:
    date_t date;
};

B.cpp:

#include <iostream>
#include "B.hpp"
using namespace std;
ostream& operator<<(ostream& output, B& b) {
    output << b.date;
    return output;
}

在这种特殊情况下,B.cpp 给出了错误no operator "<<" matches these operands; operand types are: std::basic_ostream<char, std::char_traits<char>> << date_t。我不太确定是否需要更改重载函数中的参数,或者这是否是访问问题,那么为什么会在此处抛出此错误?为了跟进,如果 B 类也使用了插入重载,它会不会有类似的问题?

标签: c++operator-overloading

解决方案


您已经operator<<在 A.cpp 中定义,但您也需要在头文件中声明它,因此其他 cpp 文件中的代码知道它。

只需添加

std::ostream& operator<<(std::ostream& output, const date_t& date);

到 A.hpp(在 的定义之后struct date_t)。您还需要添加#include <iostream>到 A.hpp。

对另一个插入运算符执行相同的操作。

您在一个 cpp 文件中定义但希望在另一个 cpp 文件中使用的任何函数或运算符都应在头文件中声明。


推荐阅读