链接错误:<lnk1120> <lnk2020>在C ++中实现一个序列化数据类</lnk2020> </lnk1120>

时间:2012-02-29 13:43:05

标签: c++ .net visual-studio-2010

我不知道为什么我在项目中有一个链接错误。我认为该类的标题和实现代码已正确实现。亲爱的朋友,我将非常感谢您的合作。

Objetive

在C ++中实现一个序列化数据类

Erros Menssage

错误2错误LNK1120:1个未解析的外部C:\ Users ... \ SerializationTest.exe 1 1 SerializationTest

错误1错误LNK2020:未解析的令牌(06000001) SerializationExtensions ^&gt; :: Serialize C:\ Users ... \ SerializationTest.obj SerializationTest

这里是代码

file:SerializationExtensions.h

#ifndef __SERIALIZATION_EXTENSIONS_H__
#define __SERIALIZATION_EXTENSIONS_H__


template<class T>
public ref class SerializationExtensions
{
public:
    static System::String^ Serialize(T obj);
    static T Deserialize(System::String^ serialized);
};


#endif // __SERIALIZATION_EXTENSIONS_H__

file:SerializationExtensions.cpp

#include "stdafx.h"
#include "SerializationExtensions.h"

#using <System.Runtime.Serialization.dll>

using namespace System::IO;
using namespace System::Xml;
using namespace System::Runtime::Serialization;

template<class T>
System::String^ SerializationExtensions<T>::Serialize(T obj)
{
    DataContractSerializer^ serializer = gcnew DataContractSerializer(obj->GetType());
    StringWriter^ writer = gcnew StringWriter();
    XmlTextWriter^ stm = gcnew XmlTextWriter(writer);
    serializer->WriteObject(stm, obj);
    return writer->ToString();
}

template<class T>
T SerializationExtensions<T>::Deserialize(System::String^ serialized)
{
    DataContractSerializer^ serializer = gcnew DataContractSerializer(typeof(T));
    StringReader^ reader = gcnew StringReader(serialized);
    XmlTextReader^ stm = gcnew XmlTextReader(reader);
    return (T)serializer->ReadObject(stm);
}

file:SerializationTest.cpp

// SerializationTest.cpp : main project file.

#include "stdafx.h"
#include "SerializationExtensions.h"


using namespace System::Collections::Generic;
using namespace System;


int main(array<System::String ^> ^args)
{

    Dictionary<System::String^, System::Double>^ teste = gcnew Dictionary<System::String^, System::Double>();
    teste->Add("Teste1",2);
    teste->Add("Teste2",4);

    Console::WriteLine(SerializationExtensions<Dictionary<System::String^, System::Double>^>::Serialize(teste));

    return 0;
}

1 个答案:

答案 0 :(得分:3)

模板类需要在标题中定义它们,因此所有想要专门化类的TU都可以看到它。

将实施移至SerializationExtensions.h