简单的类与模板

时间:2017-10-06 09:46:20

标签: class templates

我们正在尝试编写一个非常简单的类,以复数jsut为例,我们不会走得太远...

以下是我们的3个文件。

complex2.h

#include<iostream>
#include<new>

template<class T>
class complex2
{
private:
   T re, im; // real and imaginary part
public:
    complex2();
    complex2(T re_a =0.0, T im_a =0.0); //= 0.0 = 0.0

    ~complex2() {}
    T Re () const;
    T Im () const;
};

#endif // COMPLEX2_H

complex2.cpp

#include "complex2.h"

template<class T>
complex2<T>:: complex2 () {re = im = 0.0; }

template<class T>
complex2<T>:: complex2(T re_a, T im_a){re = re_a; im = im_a;}

template<class T> T complex2<T>:: Re() const { return re;}

template<class T> T complex2<T>:: Im() const {return im;}

的main.cpp

#include <iostream>
#include<cmath>
#include"complex2.h"

using namespace std;

int main()
{
    complex2<int> b(1, 2);//
    cout << "Re b: "<< b.Re() << "Im b: "<< b.Im() << endl;
    return 0;
}

从Qt运行上述内容,会显示错误消息

/home...main.cpp:10: error: undefined reference to `complex2<int>::complex2(int, int)'

/home/.../main.cpp:11: error: undefined reference to `complex2<int>::Im() const'

/home/...main.cpp:11: error: undefined reference to `complex2<int>::Re() const'

:-1: error: collect2: error: ld returned 1 exit status

有人看到我们如何才能做到这一点吗?

1 个答案:

答案 0 :(得分:1)

我认为此帖可以解决您的问题:Why can templates only be implemented in the header file?

在标题和源之间分割模板类的方式有些棘手......

此致