2

使用自制的 Complex 类时出现链接问题。

类定义:

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>. 我使用 Visual C++ 2012。如果你能给我一些关于如何解决这个问题的提示,我会非常高兴。谢谢你。

4

1 回答 1

2

声明为的函数

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.

于 2013-12-26T02:00:03.230 回答