将错误与模板类中的友元函数链接起来 [英] Linking error with friend function in template class

查看:25
本文介绍了将错误与模板类中的友元函数链接起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用自制的 Complex 类时遇到链接问题.

I have a linking problem when using a home-made Complex class.

类定义:

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).

I use the function abs like this : if(abs(z) <= 2).

这是我得到的一些错误:

Here are some errors I get:

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 而不是 Complex 时遇到了同样的错误.我使用 Visual C++ 2012.如果你给我一些关于如何解决这个问题的提示,我会很高兴.谢谢.

I get the same errors when using Complex<float> instead of Complex<long double>. I work with Visual C++ 2012. I would be really glad if you give me some hint on how to fix this. Thank you.

推荐答案

函数声明为

template <typename T>
class Complex {
    // ...
    friend T abs(Complex<T>& z);
    // ...
};

不是一个函数模板!它看起来有点像,因为它嵌套在一个类模板中,但这还不够.以下是您可能要写的内容:

is not a function template! It looks a bit like one as it is nested within a class template but that isn't quite enough. Here is what you probably meant to write:

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().

Alternatively, you could implement abs() when declaring it as friend.

这篇关于将错误与模板类中的友元函数链接起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆