【发布时间】:2016-12-11 18:19:55
【问题描述】:
我正在尝试覆盖 << 运算符,但编译器似乎无法识别我的实现,而是尝试将其解释为位移。
我已经尝试过使用参数类型(const T&、T&、T、const T)无济于事。
#pragma once
template<typename T> class AbstractStack
{
public:
virtual bool Push(const T &) = 0;
}
template <typename T> class ArrayStack : public AbstractStack <T>
{
public:
bool Push(const T&) {
....
}
}
template <typename T> bool operator<<(const AbstractStack<T>* &, const T&) {
return stack->Push(item);
}
int main() {
AbstractStack<int> *stack = new ArrayStack<int>(5);
int a = 2;
stack << a; // <<-- compiler error
return 0;
}
报错是:
Error (active) expression must have integral or unscoped enum type Lab10
Error C2296 '<<': illegal, left operand has type 'AbstractStack<int> *'
如果我将作用于类的相同运算符定义为值,它就可以工作...
【问题讨论】:
-
您只能重载具有至少一个类类型对象的运算符。对于一个参数,您有一个指针,而另一个参数是一个整数。
-
声明算子为ArrayStack的成员函数
标签: c++ operator-overloading template-classes