模板的编译问题

wu_wo 2007-08-06 01:10:13
小弟写的一个简单的程序,来验证C++ Primer上说的当模板的声明和定义在不同文件中时,可以采用包含编译模型来编译,但是怎么有错误.程序如下:
//print.h
#ifndef PRINT_H
#define PRINT_H

#include<iostream>
using namespace std;
template<class T> class print
{
public:
print(T);
void display();
private:
T data;
};
#include"print.cpp"

#endif

//print.cpp
#include"print.h"
template<class T> print<T>::print(T data0):data(data0)
{}
template<class T> void print<T>::display()
{
cout<<data<<endl;
}

//main.cpp
#include"print.h"
void main()
{
print<double> a(3.14);
a.display();
}
...全文
150 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
taodm 2007-08-06
  • 打赏
  • 举报
回复
你在C++ Primer哪个版本,哪一页看到的“C++ Primer上说的当模板的声明和定义在不同文件中时,可以采用包含编译模型来编译”
www_adintr_com 2007-08-06
  • 打赏
  • 举报
回复
#include 一个文件和直接把这个文件内容拷贝到那个地方效果是一样的。
wu_wo 2007-08-06
  • 打赏
  • 举报
回复
我只有把它的声明和定义都放头文件中去了,才能通过.那Primer上说的岂不是就错了?
www_adintr_com 2007-08-06
  • 打赏
  • 举报
回复
不要去单独编译 print.cpp 就是了,把它从工程里面移除或者改个扩展名
wu_wo 2007-08-06
  • 打赏
  • 举报
回复
如果print.cpp中不要#include"print.h",错误更多啊!
www_adintr_com 2007-08-06
  • 打赏
  • 举报
回复
print.cpp 中不要 #include"print.h" 了,要不然就循环 include 了。
taodm 2007-08-06
  • 打赏
  • 举报
回复
问题是,你是不是又在project里加了print.cpp?
老老实实把模板的所有东西都放了同一个头文件里吧。
很多知识是你暂时还无法真正掌握的,先跳过。
C++ Primer是至少要看2遍的。

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧