小编Ali*_*eda的帖子

运算符<<作为成员函数

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

c++

2
推荐指数
1
解决办法
48
查看次数

标签 统计

c++ ×1