gpt4 book ai didi

c++ - 如何将指向指针数组的指针作为参数传递给函数?

转载 作者:行者123 更新时间:2023-11-30 02:55:34 24 4
gpt4 key购买 nike

我正在尝试编写机器人代码,但遇到了一个令人困惑的情况。我需要将指向对象的指针数组传递给类的构造函数。但是,我无法在将数组传递给构造函数之前填充数组。为了解决这个问题,我想将一个指针传递给所述数组,并从该指针访问它的元素。问题是我是 C++ 的新手,所以我不确定语法。你们能帮帮我吗?

主文件代码

class RobotDemo : public SimpleRobot
{
Joystick stick;
JoystickOne joyOne;
Victor *victors [8];
public:
RobotDemo(void):
stick(1),
joyOne(&stick)// these must be initialized in the same order
// as they are declared above.
/*It doesnt seem like I can do anything but initialize things here*/
{
/*Populate array with pointers to victors. Will need to update channels*/
for (int x = 1; x <= 7; x++) {
victors[x] = new Victor(x);
}
/*And I don't think I can initialize anything here*/
myRobot.SetExpiration(0.1);
}

/**
* Drive left & right motors for 2 seconds then stop
*/
void Autonomous(void)
{
}

/**
* Runs the motors with arcade steering.
*/
void OperatorControl(void)
{
myRobot.SetSafetyEnabled(true);
while (IsOperatorControl())
{
joyOne.testForActions(); /*Check joystick one for actions*/
Wait(0.005); // wait for a motor update time
}
}
/**
* Runs during test mode
*/
void Test() {

}
};

START_ROBOT_CLASS(RobotDemo);

这是 JoystickInput 类的代码,JoystickOne 类对其进行了扩展

//the .h
#ifndef JOYSTICKINPUT_H
#define JOYSTICKINPUT_H

#include "WPILib.h"

class JoystickInput {
public:
JoystickInput(Joystick*);
JoystickInput(Joystick*, Victor* [8]);
Joystick * joystick;
bool buttons [10];
Victor** victors [8];
bool buttonClicked(int id);
virtual void testForActions();
};
#endif

//and the .cpp
#include "JoystickInput.h"

JoystickInput::JoystickInput(Joystick * joy) {
joystick = joy;
for (int x = 0; x < 10; x++) {
buttons[x] = false;
}
}
JoystickInput::JoystickInput(Joystick * joy, Victor* vicArray [8]) {
joystick = joy;
for (int x = 0; x < 10; x++) {
buttons[x] = false;
}
for (int n = 0; n <=7; n++) {
*victors[n] = vicArray[n];
}
}

bool JoystickInput::buttonClicked(int id) {
if (buttons[id] == false and joystick->GetRawButton(id) == true) {
buttons[id] = true;
return true;
} else if (buttons[id] == true and joystick->GetRawButton(id) == false) {
buttons[id] = false;
return false;
} else {
return false;
}
}

void JoystickInput::testForActions() {
}

我要你们帮我做的是重新设计 JoystickInput() 的构造函数,以便它也接受一个指向指针数组(指向 Victors)的指针,并对数组的元素执行方法。谷歌搜索没有找到任何有用的东西。我会自己研究更多,但已经过了几天,我仍然挂断了这个。

感谢您的帮助(如果不是,请至少阅读我的帖子)!

最佳答案

您应该能够使用:

JoystickInput(Joystick*, Victor**, int);

然后将 vicArray 传递给构造函数。如果 victors 可以是长度为 8 的数组之外的任何其他内容,那么您还应该将长度作为参数传递,因为 c++ 无法从指针找到数组的长度。

关于c++ - 如何将指向指针数组的指针作为参数传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16327989/

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