gpt4 book ai didi

C++ 原生于 C++/CX:如何将 std::vector 转换为 IVector?

转载 作者:行者123 更新时间:2023-11-28 07:40:17 24 4
gpt4 key购买 nike

我是 C++ 编程的新手。这些年来我做过一些 C#,但我不会说我精通它。我正在尝试将一些代码从 native c++ 更改为 C++/CX,并不断遇到很多编译器错误,特别是与 vector 有关的错误。我一直在阅读 MSDN - Collections (C++/CX)并收集到我需要使用 IVector。

我在另一个头文件中定义了一个结构:

typedef struct myStruct{
float p;
double x;
double y;
uint id;
}

我在方法声明中使用了这个结构的 vector 作为参数:

void ProcessStruct (std::vector<myStruct> myStructs){}

将其转换为 IVector 时,如下所示:

void ProcessStruct (Windows::Foundation::Collections::IVector<myStruct>^ myStructs){}

我总是遇到编译器错误 C3225 :“‘arg’的通用类型参数不能是‘type’,它必须是值类型或句柄类型”。我尝试使用 IVector<myStruct^>^相反,但后来我以 C3699 结尾:“运算符”:不能在类型“类型”上使用此间接寻址”

所以我猜我唯一的选择是创建一个通用的,但在这里我对我实际应该做什么感到非常困惑。我如何获取结构并将其转换为泛型?什么是 std::vector 做而 IVector 做不到的?

最佳答案

首先,您需要使用 Platform::Collections::Vector 而不是 std::vector。它们基本上工作相同,因为它们的行为都像 vector ,但 Platform::Collections::Vector 是一个 WRT 对象,这就是我们使用 ^(帽子指针)来处理它们的原因。

我这样使用它:

public ref class Something{
public:
property Windows::Foundation::Collections::IVector<int>^ num{
void set(Windows::Foundation::Collections::IVector<int>^ e){
NUM = static_cast<Platform::Collections::Vector>(e);
};
Windows::Foundation::Collections::IVector<int>^ get(){
return NUM;
};
};

private:
Platform::Collections::Vector<int>^ NUM;
};

在某种意义上,您将 IVector 用作属性(因为属性可以是公共(public)成员),然后将其转换为 c++/cx Vector。稍后当您需要它时,使用 IVector 作为返回 Vector 的媒介。

另请注意,set 函数的参数是一个 IVector,get 函数也是一个 IVector 类型。

一些代码来帮助:)

void Something::SomeFunction(){
num = ref new Vector<int>; //make num point to a new Vector<int>

num->Append(5); //Take the number 5 cast it from IVector to Vector
//and store it in NUM. (The cast happens due to
//the code in the IVector property we made)

int TempNum = 7 + num->GetAt(0); //Use num to get the first element of NUM and
//add 7 to it. (It's now 10, I mean 12)


num->InsertAt(0, T); //Take T (12) and replace it with the first
//element in NUM.
};

请记住,当我们对 num 做某事时,它会被强制转换,而不是对 NUM 做。这就是为什么有一个接口(interface),它们帮助我们在 Java、C# 等之间使用 Vectors(或任何其他东西,如 String 或 Map)。

关于C++ 原生于 C++/CX:如何将 std::vector 转换为 IVector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15974981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com