首页 > 解决方案 > 运算符 << 作为成员函数

问题描述

我试图弄清楚为什么我不能将重载的运算符 << 称为成员函数,就像我将 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;
}

标签: c++

解决方案


因为您将运算符设为函数模板,而函数参数不是模板类型。因此,无法解析模板参数。您需要使用模板参数调用它,例如:

a1.operator<< <void>(cout);

但这没用,因为没有使用模板参数。您要么需要T是函数参数的类型:

template <class T> ostream& operator<<(T&);

或者只是让它成为一个普通的功能,因为它看起来不像你需要它成为一个模板:

ostream& operator<<(ostream& o);

推荐阅读