gpt4 book ai didi

c++ - C++中的模板类重载运算符ostream不起作用

转载 作者:行者123 更新时间:2023-12-03 07:09:42 26 4
gpt4 key购买 nike

所以我有这个模板类:

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声明声明了一个非模板operator<<,但它被定义为模板,它们不匹配。
您可以引用操作符模板来制作friend声明,例如

// forward declaration
template<class T = int, unsigned int SIZE =2>
class FixedPoint;

// declaration
template<class T,unsigned int SIZE>
std::ostream& operator<<(std::ostream& os ,const FixedPoint<T,SIZE>& price);

template<class T, unsigned int SIZE>
class FixedPoint {
public:
...
friend std::ostream& operator<< <T, SIZE> (std::ostream& os ,const FixedPoint<T, SIZE>& price);
// or just
// friend std::ostream& operator<< <> (std::ostream& os ,const FixedPoint& price);
...
};

// definition
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;
}

关于c++ - C++中的模板类重载运算符ostream不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64606644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com