不知道为什么会产生链接错误。任何线索?
数据流.h
#ifndef DATASTREAM_H
#define DATASTREAM_H
#include <vector>
#include <iostream>
class idatastream
{
public:
idatastream();
template<class T>void write(T data);
bool SetPosition(int position);
void print();
private:
int m_position;
std::vector<char> m_buffer;
};
#endif DATASTREAM_H
数据流.cpp
#include "datastream.h"
idatastream::idatastream()
{
m_position = 0;
}
template<class T>
void idatastream::write(T data)
{
char * getPtr = (char *)&data
int index = 0;
if(m_buffer.size() < m_position)
{
resize(m_position);
for(int i = m_position; i < m_position + sizeof(T); i++)
{
m_buffer.push_back(getPtr[index]);
index++;
m_position++;
}
}
else if(m_buffer.size() == m_position)
{
for(int i = m_position; i < m_position + sizeof(T); i++)
{
m_buffer.push_back(getPtr[index]);
index++;
m_position++;
}
}
else
{
for(int i = m_position; i < m_position + sizeof(T); i++)
{
m_buffer[m_position] = getPtr[index];
index++;
m_position++;
}
}
return;
}
bool idatastream::SetPosition(int position)
{
if (position >= 0)
{
m_position = position;
return true;
}
else
{
return false;
}
}
void idatastream::print()
{
for(int i = 0; i < (int) m_buffer.size(); i++)
{
std::cout << m_buffer[i] << " ";
}
std::cout << " \n";
}
主文件
#include "datastream.h"
int main()
{
idatastream test;
int meh = 6;
int peh = 23;
int teh = 65;
test.write<int>(meh);
test.write<int>(peh);
test.write<int>(teh);
test.print();
return 0;
}
错误:
error LNK2019: unresolved external symbol "public: void __thiscall idatastream::write<int>(int)" (??$write@H@idatastream@@QAEXH@Z) referenced in function _main
我只是在定义这个模板函数时犯了一个愚蠢的错误,还是 msvc 只是给我带来了麻烦?另外,如果你想在这里批评我的代码,请继续,但如果它是这样的,“哇,这是有史以来最糟糕的代码,这里用我很棒的东西代替”,无论多么正确,它都可能被忽略你是。