繁体   English   中英

指向同一数组的多个对象

[英]Multiple Objects pointing to same array

我在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上收到错误消息说表达式必须是可修改的值

我没有麻烦显示构造函数,复制构造函数和Destructor。 我知道通常在析构函数中应该删除指针,但是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);

注意删除了*

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM