指向同一数组的多个对象

Multiple Objects pointing to same array

本文关键字:对象 数组      更新时间:2023-10-16

我对在C++中使用指针相当陌生,但我会尝试解释我想做什么。

我有一个类对象 Rx(接收器),在我的程序中,我将同时使用多个接收器。每个接收器都有一个数据向量(观察),为简单起见,我只使用一个双精度向量。我还有一个布尔数组,用于确定使用哪些观察值,我希望每个接收器(作为成员变量)都有一个指向该数组的指针。例如,布尔数组中的第一个元素会说"真或假使用你拥有的第一个观察值接收器"。

此外,在我的代码中,我还想指向一个对象数组,我会遵循相同的过程吗?

int main()
{
    // The elements in this array are set in the code before
    bool use_observations[100];
    // I have chosen 3 for an example but in my actual code I have a vector
    // of receivers since the quantity varies
    Rx receiver_1, receiver_2, receiver_3;
    // I would like to set the pointer in each receiver to point
    // to the array use_observations
    receiver_1.SetPointer(use_observations);
    receiver_2.SetPointer(use_observations);
    receiver_3.SetPointer(use_observations);
} // end of main()

我的接收器类声明和定义:

class Rx{
public:
    Rx(); // Constructor
    Rx(const Rx& in_Rx); // Copy constructor
    ~Rx(); // Destructor
    void SetPointer(bool* in_Array); // Function to set pointer to use_observation
private:
    std::vector<double> data;
    bool* pointer_to_array[10];
}; // end of class Rx
void Rx::SetPointer(bool* in_Array)`{*pointer_to_array`= in_Array);

这就是我遇到问题的地方,要么它没有正确分配(获取大量空值或未分配),要么我在说表达式必须是可修改值pointer_to_array出现错误

我没有费心显示构造函数、复制构造函数和析构函数。我知道通常在析构函数中您应该删除指针,但是 Rx 不拥有数组中的数据,所以我不想删除它。感谢您的帮助

编辑**我已经展示了一些我正在使用的代码以及我得到的结果,我已经修改了SetPointer()以显示一些结果

int main
{
bool use_observations [6] = {true, true, true, true, true, true};
Rx receiver_1;
receiver_1.SetPointer(use_observations);
}
void Rx::SetPointer(bool* in_Array)
{
*pointer_to_array = in_Array;
for(int i = 0; i < 6; i++)
{
    if(*pointer_to_array[i] == true)
        std::cout << "Good" << std::endl;
} // end of for loop
} // end of SetPointer()

当我调试并单步执行(*pointer_to_array = in_Array)时,我得到结果{true,其余元素0xCCCCCCCC},然后在 for 循环的第二次迭代中崩溃,说"访问冲突读取位置0xCCCCCCCC

第二次编辑 **谢谢大家的帮助。@PaulMcKenzie在他的Rx实现(在评论中)中指出,我应该有bool*pointer_to_array而不是bool* pointer_to_array[6],这解决了这个问题。同样,我应该指向数组缓冲区的开头,而不是指向数组的指针。

问题是你想要一个指向数组缓冲区开头的指针,而不是指向数组的指针。

class Rx{
public:
    void SetPointer(bool* in_Array); 
    bool* pointer_to_array;
};
void Rx::SetPointer(bool* in_Array) {pointer_to_array = in_Array);

请注意删除*