我有一个包含vector的结构如下:
struct MY_STRUCT
{
LONG lVariable;
CString strVariable;
BOOL bVariable;
vector<MY_ANOTHER_STRUCT> vecAnotherStruct;
};
我还有一个用于存储 MY_STRUCT 数据类型的CArray:
CArray<MY_STRUCT> arMyStruct;
我可以将 MY_STRUCT 类型的元素添加到 arMyStruct 中,我添加的所有元素都会在“监视”窗口中正确显示。
当我尝试从CArray获取元素时出现问题。
// This line gives access violation error message.
MY_STRUCT structVariable = arMyStruct[0];
// This line work correctly
MY_STRUCT& structVariable = arMyStruct[0];
任何人都可以指出为什么第一行不起作用?
编辑:
以下是我认为可能有助于缩小问题范围的进一步细节:
我的课程包含 MY_STRUCT 和 arMyStruct 的定义,如下所示
class MyClass
{
struct MY_STRUCT
{
LONG lVariable;
CString strVariable;
BOOL bVariable;
vector<MY_ANOTHER_STRUCT> vecAnotherStruct;
};
CArray<MY_STRUCT> arMyStruct;
void function()
{
// This line gives access violation error message
// when trying to access from here
MY_STRUCT structVariable = arMyStruct[0];
}
};
void someFunction()
{
MyClass myClass;
MyClass::MY_STRUCT aStruct;
// initialize structure and add some data to vector
myClass.arMyStruct.Add(aStruct);
// This line work fine
// when trying to access from here
MY_STRUCT structVariable = arMyStruct[0];
// When trying to access CArray element from below function,
// gives access violation error message
myClass.function();
}
答案 0 :(得分:0)
第一行不起作用,因为您省略了CArray定义的第二个参数:
CArray<MyType, MyType> myArray;
该参数定义(如果我没有错),您如何访问数组元素。省略它,编译器得到默认值:
CArray<MyType, MyType&> myArray;
这应该是首先不起作用的原因,后者是。
更新:
我已经尝试过您的代码......如果您进行了这些更正,它就会起作用:
class MyClass{
public:
struct MY_ANOTHER_STRUCT
{
float foo;
};
struct MY_STRUCT
{
LONG lVariable;
CString strVariable;
BOOL bVariable;
vector<MY_ANOTHER_STRUCT> vecAnotherStruct;
};
CArray<MY_STRUCT> arMyStruct;
void function()
{
// This line gives access violation error message
// when trying to access from here
MY_STRUCT structVariable = arMyStruct[0];
}
};
void someFunction()
{
MyClass myClass;
MyClass::MY_STRUCT aStruct;
// initialize structure and add some data to vector
myClass.arMyStruct.Add(aStruct);
// This line work fine
// when trying to access from here
MyClass::MY_STRUCT structVariable = myClass.arMyStruct[0];
// When trying to access CArray element from below function,
// gives access violation error message
myClass.function();
}