我是使用模板的新手,还为它们重载了运算符。这是我的简单代码。我试着写一个 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;
}
我不知道:
- 为什么我遇到这个错误。
- 那种错误是什么。
- 以及如何解决该问题并使代码成功运行。
你能帮我解决以上问题吗?
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::val
是private
,您还必须将其声明为 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/