首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带有模板的简单类

带有模板的简单类
EN

Stack Overflow用户
提问于 2017-10-06 09:46:19
回答 1查看 24关注 0票数 0

我们试图编写一个非常简单的类,以复数jsut为例,而且我们没有取得很大的进展。

下面是我们的3个文件。

络合2.h

代码语言:javascript
复制
#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

络合2.complex2.cpp

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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运行上面的代码,将提供错误消息。

代码语言:javascript
复制
/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

有谁知道我们怎样才能做到这一点吗?

EN

回答 1

Stack Overflow用户

发布于 2017-10-06 09:51:40

我认为这篇文章解决了你的问题:Why can templates only be implemented in the header file?

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

问候

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46602936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档