用类fnc中的数据填充向量

fill vector with data inside a class fnc

本文关键字:填充 向量 数据 fnc 用类      更新时间:2023-10-16

我有一个自定义的数据类型数组和向量,如下所示。在Foo函数中,我开始用数据填充数组和向量。无论如何,用数据填充数组是没有问题的。然而,我无法使用vector访问任何内容。我找不到我缺少的东西。

有没有一种方法可以用数据填充矢量对象。

// MyClass.h
#include <cliext/vector>
using namespace System;
using namespace cliext;
public ref class MyClass {
private :
static int x ;
static float y ;
String ^name;
public :
static array<MyClass ^> ^myArray = gcnew array <MyClass^> (3) ;
static vector<MyClass^> ^myVector = gcnew vector <MyClass^> (3) ;
void Foo();
};
// MyClass.cpp
#include "stdafx.h"
#include <MyClass.h>
void MyClass::Foo()
{
myArray[0] = gcnew MyClass;
myVector[0] = gcnew MyClass;
myArray[0]->x = 100 ;
myArray[0]->x = 99.5 ;
myArray[0]->name = "Good" ;
myVector[0]->CAN'T ACCESS ANY CLASS DATA MEMBER !!
}

下面是MSDN,它解释了正在发生的事情:如何:从程序集中暴露STL/CLR容器

"STL/CLR容器(如list和map)是作为模板引用类实现的。因为C++模板是在编译时实例化的,所以两个签名完全相同但位于不同程序集中的模板类实际上是不同的类型。这意味着模板类不能跨程序集边界使用。"

据我所知,您的公共类正试图导出向量的模板专用化,但这将具有与同一向量的外部声明不同的签名,并且永远不会匹配。

您可能想要像这样更改myVector元素(它为我编译):

static cliext::vector<MyClass^>::generic_container ^myVector = gcnew cliext::vector<MyClass^>(3); 

另一种选择是不将类标记为"public",这样编译器就不会试图使其在程序集之外可用。

我还要注意,在x和y上使用"static"在我看来是可疑的。你确定你只想要其中一个吗?