当我使用自制的复杂课程时,我遇到了连接问题。
类别定义:
template<class T>
class Complex
{
public:
Complex(const T real = 0, const T imag = 0);
Complex(const Complex<T>& other);
~Complex(void) {};
Complex<T> operator*(const Complex<T>& other) const;
Complex<T> operator/(const Complex<T>& other) const;
Complex<T> operator+(const Complex<T>& other) const;
Complex<T> operator-(const Complex<T>& other) const;
friend void operator*=(const Complex<T>& z,const Complex<T>& other);
friend void operator/=(const Complex<T>& z,const Complex<T>& other);
friend void operator+=(const Complex<T>& z,const Complex<T>& other);
friend void operator-=(const Complex<T>& z,const Complex<T>& other);
void operator=(const Complex<T>& other);
friend T& real(Complex<T>& z);
friend T& imag(Complex<T>& z);
friend T abs(Complex<T>& z);
friend T norm(Complex<T>& z);
private:
T real_;
T imag_;
};
实施abs:
template<class T>
T abs(Complex<T>& z)
{
return sqrt(z.real_*z.real_ + z.imag_*z.imag_);
}
我使用abs这样的函数:if(abs(z) <= 2)
。
以下是我遇到的一些错误:
Error 4 error LNK2001: unresolved external symbol "long double __cdecl abs(class Complex<long double> &)" (?abs@@YAOAAV?$Complex@O@@@Z) C:\Users\Lucas\Documents\Visual Studio 2012\Projects\Fractals\Fractals\Main.obj Fractals
Error 3 error LNK2001: unresolved external symbol "long double & __cdecl imag(class Complex<long double> &)" (?imag@@YAAAOAAV?$Complex@O@@@Z) C:\Users\Lucas\Documents\Visual Studio 2012\Projects\Fractals\Fractals\Main.obj Fractals
在使用Complex<float>
而不是Complex<long double>
时,我也会遇到同样的错误。我使用的是VisualC++ 2012。如果你能给我一些关于如何解决这个问题的建议,我会很高兴的。谢谢。
发布于 2013-12-26 02:00:03
声明为
template <typename T>
class Complex {
// ...
friend T abs(Complex<T>& z);
// ...
};
不是函数模板!它看起来有点像一个类模板,因为它嵌套在类模板中,但这还不够。以下是您可能要写的内容:
template <typename T> class Complex;
template <typename T> T abs(Complex<T>&);
template <typename T>
class Complex {
// ...
friend T abs<T>(Complex<T>& z);
// ...
};
或者,您可以在将abs()
声明为friend
时实现它。
https://stackoverflow.com/questions/20778299
复制相似问题