簡體   English   中英

將錯誤與模板類中的友元函數鏈接起來

[英]Linking error with friend function in template class

使用自制的 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。如果你給我一些關於如何解決這個問題的提示,我會很高興。 謝謝你。

函數聲明為

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);
    // ...
};

或者,您可以在將其聲明為friend時實現abs()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM