【问题标题】:Issues on using operator<< for templates in C++ for a newbie关于在 C++ 中为新手使用 operator<< 的问题
【发布时间】:2016-01-10 16:08:42
【问题描述】:

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

#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)

【问题讨论】:

  • 请重新输入错误而不是屏幕截图。屏幕截图不好用谷歌搜索。

标签: c++ class templates operator-overloading


【解决方案1】:

这个重载的操作符:

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

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

解决方案:

operator&lt;&lt; 应该做一些真正的工作,打印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&lt;&lt;

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

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

【讨论】:

  • 我公开了 val 但仍然出现该错误。你知道怎么解决吗?
  • “我想operator&lt;&lt; 应该做一些真正的工作,打印to.val。” - 我写道。你也这样做了吗?
  • 问题不在于做一些真正的工作!我需要了解这件事,然后我认为使用这些新术语可以更好地工作。 :) 你的代码仍然不能工作:(
  • @franky 错误抱歉,now it works
【解决方案2】:
template <class T> ostream& operator<<(ostream& os, T& to) {
    return (os << to);
}

以上是递归调用。函数永远调用自己,直到进程吃光调用堆栈。

【讨论】:

  • ... 或手动终止以将计算机转换为非常昂贵的空间加热器,特别是如果编译器成功内联。
猜你喜欢
  • 2012-01-03
  • 2021-10-11
  • 1970-01-01
  • 2011-02-01
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
相关资源
最近更新 更多