【发布时间】:2013-12-05 15:04:10
【问题描述】:
这是 C++ 中一个非常疯狂的定点算术实现。拜托,请不要告诉我这一切有多糟糕和毫无意义。
如您所见,有一个基本类型T和一个二进制数字的小数部分N。需要将FixedNum<int, A> + FixedNum<int, B> 评估为FixedNum<int, MAX(A, B)>. 这是我尝试实现它的方法。但是,GCC 说最后几行中对x 的分配是错误的,因为x 是受保护的。怎么了?
#define MAX(a,b) (((a)>(b))?(a):(b))
template <typename T, int N>
class FixedNum
{
public:
template <int N2>
friend FixedNum& operator+(const FixedNum& f, const FixedNum& g);
template <int N2>
friend FixedNum& operator+=(const FixedNum& f, const FixedNum& g);
FixedNum(T x): x (x) {}
T num() const { return x; }
int point() const { return N; }
protected:
T x;
};
template <typename T, int N, int N2>
FixedNum<T, MAX(N, N2)>& operator+(const FixedNum<T, N>& f, const FixedNum<T, N2>& g)
{
return FixedNum<T, N>(f) += g;
}
template <typename T, int N, int N2>
FixedNum<T, MAX(N, N2)>& operator+=(const FixedNum<T, N>& f, const FixedNum<T, N2>& g)
{
#if N2 <= N
f.x += g.x << (N-N2);
#else
f.x <<= (N2-N);
f.x += g.x;
#endif
}
【问题讨论】:
-
x确实受到保护,显然您正试图将 operator+= 声明为朋友。但我认为您的朋友声明与您实现的运算符不匹配。 -
我不相信模板的不同专业可以相互访问
protected变量,除非专业是朋友。见stackoverflow.com/questions/11001480/…
标签: c++ templates operator-overloading friend