C++类模板使用的问题

[复制链接]
查看11 | 回复4 | 2010-5-24 10:44:54 | 显示全部楼层 |阅读模式
编了个Array类模板:
//array.h
#ifndef ARRAY_H
#define ARRAY_H
#include
using namespace std;
template
class Array
{
public:
int getSize() const;
T &operator[]( int );
T operator[]( int ) const;
private:
T array[ size ];
};
#endif
//array.cpp
#include"array.h"
#include
#include
using namespace std;
template
int Array::getSize() const
{
return size;
}
template
T &Array::operator[]( int subscript )
{
if( subscript = size )
{
cerr
T Array::operator[]( int subscript ) const
{
if( subscript = size )
{
cerra;
int i;
for( i = 0; i < a.getSize(); i++ )
a[ i ] = i;
return 0;
}
运行时会报错:
Linking...
main.obj : error LNK2001: unresolved external symbol "public: int & __thiscall Array::operator[](int)" (??A?$Array@H$09@@QAEAAHH@Z)
main.obj : error LNK2001: unresolved external symbol "public: int __thiscall Array::getSize(void)const " (?getSize@?$Array@H$09@@QBEHXZ)
Debug/new.exe : fatal error LNK1120: 2 unresolved externals
我找不到错误在哪里。。。哪位帮我看看吧。。。

回复

使用道具 举报

千问 | 2010-5-24 10:44:54 | 显示全部楼层
将你的array.cpp全部放在与main函数相同的文件中。因为在连接时,编译系统没有找到你所定义的操作。没有#include*.cpp 的写法,但你的两个.cpp之间又没有联系,当然在编译的时候会出错了。
回复

使用道具 举报

千问 | 2010-5-24 10:44:54 | 显示全部楼层
我只是知道,如果你把头文件和cpp都写在main函数里面就能编译过原因我也不明白
回复

使用道具 举报

千问 | 2010-5-24 10:44:54 | 显示全部楼层
因为类模板的定义和实现必须放在同一个文件中,否则就会出错。你把array.cpp的内容放入到array.h中试一试。
回复

使用道具 举报

千问 | 2010-5-24 10:44:54 | 显示全部楼层
目前 c++ 的模板实现只能和模板定义写在同一个文件,c++0x 可能会有所改进,允许分开写。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行