c++ - 运算符 << 作为成员函数

标签 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);

关于c++ - 运算符 << 作为成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56509868/

相关文章:

html - 尝试使用正则表达式提取一段HTML代码

c++ - Doxygen - 将参数声明为可选

c++ - std::views 尚未声明

python - xtensor 和 xsimd : improve performance on reduction

c++ - 类模板偏特化 : compiler error

c++ - 不同编译器的 C++ 类型的大小

c++ - 如何使用 OpenImageIO 和 read_tiles() 读取平铺图像

c# - C++/CLI 等效于 C# checked 关键字

c++ - 使用哪一个 - memmove() 或 memcpy() - 当缓冲区不重叠时?

c++ - 使用默认模板参数引入派生类型