c++ - 为什么在这种情况下覆盖流插入运算符时会出现“未找到运算符”错误?
问题描述
我有一个包含多个头文件和源文件的项目,我已将其缩短为我认为在这里很重要的内容(尽管我可能是错的)。它们看起来像这样:
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 类也使用了插入重载,它会不会有类似的问题?
解决方案
您已经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 文件中使用的任何函数或运算符都应在头文件中声明。
推荐阅读
- ansible - Ansible 中基于 vars_prompt 有条件地导入剧本
- excel - 有没有办法获取活动选择范围的索引?
- javascript - MongoDB中的查询优化
- sql - Oracle 查询:如何将返回的记录限制为仅计数 > 1 但显示完整结果的记录?
- python - 如何使用 TFF api 进行自定义使用?
- html - 为什么数字“1”和“2”不带下划线?
- microsoft-graph-api - OneDrive Personal 列表版本 API 不提供当前版本的唯一 ID
- java - Maven 部署不断询问用户名/密码
- javascript - React-native:如何将字节数组(缓冲区数据)转换为位(二进制数据)
- swift - 从现有的 SwiftUI @States 派生绑定