我不知道为什么我在项目中有一个链接错误。我认为该类的标题和实现代码已正确实现。亲爱的朋友,我将非常感谢您的合作。
在C ++中实现一个序列化数据类
错误2错误LNK1120:1个未解析的外部C:\ Users ... \ SerializationTest.exe 1 1 SerializationTest
错误1错误LNK2020:未解析的令牌(06000001) SerializationExtensions ^> :: Serialize C:\ Users ... \ SerializationTest.obj SerializationTest
#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__
#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);
}
// 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;
}
答案 0 :(得分:3)
模板类需要在标题中定义它们,因此所有想要专门化类的TU都可以看到它。
将实施移至SerializationExtensions.h
。