【发布时间】:2021-02-12 19:31:32
【问题描述】:
所以我有这个模板类:
template<class T = int, unsigned int SIZE =2>
class FixedPoint {
public:
explicit FixedPoint(T dollars = 0);
FixedPoint(T dollars, T cents);
friend std::ostream& operator<<(std::ostream& os ,const FixedPoint& price);
private:
static long digitsAfterDotFactor();
long sizeAfterDot;
T dollars;
T cents;
};
这是它在 h 文件中的类下的定义
template<class T,unsigned int SIZE>
inline std::ostream& operator<<(std::ostream& os ,const FixedPoint<T,SIZE>& price){
os << price.dollars << "." << price.cents;
return os;
}
代码给了我以下错误:
friend declaration ‘std::ostream& operator<<(std::ostream&, const FixedPoint<T, SIZE>&)’ declares a non-template function
我尝试在声明中添加模板名称,但它无法识别 T 类,我该怎么办?我应该为每种类型制作规范模板吗?
【问题讨论】:
-
如果你想要类定义之外的函数定义,将
friend声明更改为friend std::ostream& operator<<(std::ostream& os ,const FixedPoint<T, SIZE> & price)(即提供模板参数)。我假设<iostream>(或者,更好的是<iosfwd>)之前已包含在内。 -
附注:
os << price.dollars << "." << price.cents;会将 1 美元和 5 美分打印为1.5而不是1.05。 -
是的,谢谢,我知道,我只是一次解决一个问题,哈哈,编译时错误需要更多注意。
标签: c++ templates operator-overloading friend ostream