我有这样一门课:
namespace N
{
template<unsigned Mantissa, unsigned Fraction>
class C
{
//...
public:
friend C<Mantissa, Fraction> operator +(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right);
//...
};
}我一直在尝试分别定义这个operator +,但是我无法让它工作。
我试过:
template<unsigned Mantissa, unsigned Fraction>
N::C<Mantissa, Fraction> N::operator+(const N::C<Mantissa, Fraction> & left, const N::C<Mantissa, Fraction> & right)
{
//...
}但我得到了"C2244‘运算符+':无法将函数定义与现有声明相匹配“
我试过:
template<unsigned Mantissa, unsigned Fraction>
N::C<Mantissa, Fraction> operator+(const N::C<Mantissa, Fraction> & left, const N::C<Mantissa, Fraction> & right)
{
//...
}但我有链接错误。
我试过:
namespace N
{
template<unsigned Mantissa, unsigned Fraction>
C<Mantissa, Fraction> operator+(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right)
{
//...
}
}但我也有同样的链接错误。
我不知道问题是什么,也不知道如何解决。operator必须是一个friend,因为它正在访问一个private字段(否则,我将不得不将字段设置为public,如果可以避免的话,我不想这样做)。
发布于 2017-05-01 13:44:53
operator+在类定义中被声明为非模板函数,但是您试图在以后将它定义为函数模板,它们不匹配。如果要使其成为函数模板,则可以
namespace N
{
// forward declaration of the class template
template<unsigned Mantissa, unsigned Fraction>
class C;
// forward declaration of the function template
template<unsigned Mantissa, unsigned Fraction>
C<Mantissa, Fraction> operator +(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right);
template<unsigned Mantissa, unsigned Fraction>
class C
{
//...
public:
// the instantiation of operator+ with template parameter of current Mantissa and Fraction becomes friend
friend C<Mantissa, Fraction> operator + <>(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right);
// ~~
//...
};
}
// definition of the function template
template<unsigned Mantissa, unsigned Fraction>
N::C<Mantissa, Fraction> N::operator+(const N::C<Mantissa, Fraction> & left, const N::C<Mantissa, Fraction> & right)
{
//...
}如果您想使它成为非模板函数,那么只需在类定义中定义它:
namespace N
{
template<unsigned Mantissa, unsigned Fraction>
class C
{
//...
public:
// defined as non-template
friend C<Mantissa, Fraction> operator +(const C<Mantissa, Fraction> & left, const C<Mantissa, Fraction> & right) {
//...
}
//...
};
}https://stackoverflow.com/questions/43720007
复制相似问题