c++ - 新手在 C++ 中将 operator<< 用于模板的问题

标签 c++ class templates operator-overloading

我是使用模板的新手,还为它们重载了运算符。这是我的简单代码。我试着写一个 operator<<对于类型 T ,但遇到了一些奇怪的错误!

#include <iostream>
using namespace std;

template <class T>
class S {
    T val;

public:
    S<T>(T v) { val = v; }
};

template <class T>
ostream& operator<<(ostream& os, T& to) {
    return (os << to);
}

template <class T>
void write_val(T& t) {
    cout << t << endl;
}

int main()
{
    S<int> s1(5);
    write_val(s1);

    return 0;
}

我不知道:

  1. 为什么我遇到这个错误。
  2. 那种错误是什么。
  3. 以及如何解决该问题并使代码成功运行。

你能帮我解决以上问题吗?

PS:这是一个更大的代码的一小部分。我将此部分分开,因为我认为这是我的问题的根源。

错误:

Unhandled exception at 0x00EEC529 in test3.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00342F8C)

最佳答案

这个重载运算符:

template <class T> ostream& operator<<(ostream& os, T& to) {
    return (os << to);
}

递归调用自身,您可以在调用堆栈 窗口中看到它。继续阅读 Call Stack了解它是如何工作的以及为什么和何时stack overflow发生。我的意思是,这个网站叫做 Stack Overflow,难道你不想知道它代表什么吗?

解决方案:

operator<<应该做一些真正的工作,打印 to.val , 我想。自 S::valprivate ,您还必须将其声明为 S 的友元函数.

template <class T>
class S {
    T val;

    template <class U>
    friend ostream& operator<<(ostream& os, S<U> const& to); // add some const

public:
    S<T>(T v) : val(v) {} // use member initializer list
};

template <class U>
ostream& operator<<(ostream& os, S<U> const& to) {
    return os << to.val;
}

不要重载 operator<<像这样:

template <class T>
ostream& operator<<(ostream& os, T& to);

因为该模板将匹配(几乎)所有内容。

关于c++ - 新手在 C++ 中将 operator<< 用于模板的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34707649/

相关文章:

c++ - VS2005 C++ 损坏的虚表

c++ - 无法运行 Makefile.am,我该怎么办?

c++ - 为什么这个 SFINAE 在 gcc 中会报错?

python - ctypes库如何实现基本数据类型乘法来生成数组?

c++ - 在链表程序中使用模板时在 C++ 中重载 << 运算符

c++ - CLI/C# 类中属性的特殊访问控制

java - 您是否有办法在程序运行时重写类(或者更改我猜的最终值)

php - 在一个类中拥有相当数量的公共(public)属性是否合理?

javascript - 如何在vue模板中按行分割内联JS表达式?

c++ - 关于C++模板的问题