我有一个包含在System::Collections::Queue中的数据流。我的数据源可以将相同的数据输出到多个流,但要这样做,需要为每个流复制数据。我目前做了以下工作:
void DataGatherer::AddMyDataToQueues(MyData^ data)
{
// Send duplicates to all queues
for( int i = 0; i < m_outputQueues->Count; i++ )
{
AddResultToQueue(gcnew MyData(data), (Queue^)m_outputQueues[i]);
}
}只要我发送的是MyData对象,它就能正常工作。假设我也想发送MyOtherData对象。如果能像这样做一些更通用的事情就好了:
void DataGatherer::AddDataToQueues(Object^ obj)
{
// Send duplicates to all queues
for( int i = 0; i < m_outputQueues->Count; i++ )
{
AddResultToQueue(gcnew Object(obj), (Queue^)m_outputQueues[i]);
}
}无法编译的...but,因为:
1>.\DataGatherer.cpp(72) : error C3673: 'System::Object' : class does not have a copy-constructor那么,在不知道对象类型的情况下复制对象是可能的吗?..and如果是,我该怎么做?:)
发布于 2010-02-13 19:43:57
让MyData和MyOtherData都实现ICloneable,然后更改AddDataToQueues以接受任何实现ICloneable的对象。
public ref class MyOtherData : public ICloneable
{
public:
MyOtherData()
: m_dummy(-1)
{
}
virtual Object^ Clone()
{
MyOtherData ^clone = gcnew MyOtherData();
clone->m_dummy = m_dummy;
return clone;
}
private:
int m_dummy;
};然后..。
void DataGatherer::AddDataToQueues(ICloneable^ data)
{
// Send duplicates to all queues
for( int i = 0; i < m_outputQueues->Count; i++ )
{
AddResultToQueue(data->Clone(), (Queue^)m_outputQueues[i]);
}
}https://stackoverflow.com/questions/2251393
复制相似问题