c++ - 运算符 << 作为成员函数
问题描述
我试图弄清楚为什么我不能将重载的运算符 << 称为成员函数,就像我将 operator+ 称为成员函数一样。
#include "pch.h"
#include <iostream>
using namespace std;
class A
{
int x;
public: A(int i = 0) { x = i; }
A operator+(const A& a) { return x + a.x; }
template <class T> ostream& operator<<(ostream&);
};
template <class T>
ostream& A::operator<<(ostream& o) { o << x; return o; }
int main()
{
A a1(33), a2(-21);
a1.operator+(a2);
a1.operator<<(cout); // Error here
return 0;
}
解决方案
因为您将运算符设为函数模板,而函数参数不是模板类型。因此,无法解析模板参数。您需要使用模板参数调用它,例如:
a1.operator<< <void>(cout);
但这没用,因为没有使用模板参数。您要么需要T
是函数参数的类型:
template <class T> ostream& operator<<(T&);
或者只是让它成为一个普通的功能,因为它看起来不像你需要它成为一个模板:
ostream& operator<<(ostream& o);
推荐阅读
- python - Python regex:重命名所有文件,但名称中包含今天日期的文件除外
- java - 将 Apache Beam 的 PCollection 对象收集到驱动程序的内存中
- c# - 如何从 C# 中的抽象列表中访问派生类的成员变量
- matlab - 神经网络的学习曲线
- excel - 有没有一种快速的方法可以在 Excel 中有效地嵌套公式或填充公式参数?
- haskell - Haskell - 返回给定列表中大于 n 的数字
- java - 如何在java 8中将列表转换为具有设定值的地图
- ios - 在相机 iOS 上绘制叠加层
- reactjs - 在 ReactJS 项目中自动导入所有 *.scss
- c# - 从字符串中读取字符并计算每个字符