指向同一数组的多个对象
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出现错误
我没有费心显示构造函数、复制构造函数和析构函数。我知道通常在析构函数中您应该删除指针,但是 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);
请注意删除*
。
- 将对象数组的引用传递给函数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 类对象数组的问题会导致崩溃
- Arduino C++在构造函数中用参数声明对象数组
- 使用对象数组对 SFML 进行动画处理
- C++ 对象数组堆栈溢出
- 如何将对象数组作为参数传递给模板
- 使用向量初始化参数化构造函数的对象数组
- 如何初始化对象数组?
- C++创建对象数组
- 在对象数组中搜索字符串并返回相应值的函数
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 编译时生成应在构造函数中创建的非 constexpr 对象数组
- 使用 C++ 创建对象数组
- 对象数组打印空白字符串
- 重载运算符 [] 用于从对象数组中给出特定索引
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组