0

我正在为移动机器人制作一个 .lib 文件。目前我正在编写一个扫描蓝牙设备的函数。

功能是:

struct Device
{
     string DeviceName;
     BTH_ADDR DeviceAddress;
};

void ScanForDevices(vector<Device> *Robot)
    {
        m_bt = BluetoothFindFirstRadio(&m_bt_find_radio, &m_radio);

        BluetoothGetRadioInfo(m_radio, &m_bt_info);
        m_search_params.hRadio = m_radio;

        ZeroMemory(&m_device_info, sizeof(BLUETOOTH_DEVICE_INFO));
        m_device_info.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);

        m_bt_dev = BluetoothFindFirstDevice(&m_search_params, &m_device_info);


        int m_device_id = 0;
        char charDeviceName[250];

        do {
                charDeviceName[250]=NULL;
                Robot->push_back(Device()); 
                //WideCharToMultiByte(CP_UTF8,0,m_device_info.szName,-1, charDeviceName,0,NULL, NULL);
                WideCharToMultiByte(CP_UTF8,0,m_device_info.szName,-1, charDeviceName,250,NULL, NULL);
                Robot[m_device_id]->DeviceName=(string)charDeviceName;
                Robot[m_device_id]->DeviceAddress=m_device_info.Address.ullLong;
                m_device_id++;

            } while(BluetoothFindNextDevice(m_bt_dev,&m_device_info));

            BluetoothFindDeviceClose(m_bt_dev);

            BluetoothFindRadioClose(m_bt);
    }

我不断得到:

Error   6   error C2819: type 'std::vector<_Ty>' does not have an overloaded member 'operator ->'
Error   7   error C2039: 'DeviceName' : is not a member of 'std::vector<_Ty>'
Error   8   error C2819: type 'std::vector<_Ty>' does not have an overloaded member 'operator ->'
Error   9   error C2039: 'DeviceAddress' : is not a member of 'std::vector<_Ty>'
Error   10  IntelliSense: expression must have pointer type 
Error   11  IntelliSense: expression must have pointer type 

我正在开始使用 C++,但对指针的使用并不十分熟练。

欢迎任何帮助。

4

2 回答 2

1

机器人是一个指向 的指针vector<Device>。您对指向向量和向量元素的访问感到困惑。要解决此问题,您可以更改:

Robot[m_device_id]->DeviceName=(string)charDeviceName;

Robot->at(m_device_id).DeviceName = std::string(charDeviceName);

或者

(*Robot)[m_device_id].DeviceName = std::string(charDeviceName);

建议

更好的解决方案是通过引用而不是指针传递向量。

void ScanForDevices(vector<Device> &Robot)
{
    std::string  charDeviceName;   //<<-- use std::string instead of char array
    Robot[m_device_id].DeviceName = charDeviceName;  //<<-- this is better coding style
}
于 2013-06-09T10:43:10.390 回答
1

要按索引访问vector<Device> *Robot元素,请使用以下语法:

(*Robot)[m_device_id]

您的代码应该是:

(*Robot)[m_device_id].DeviceName=(string)charDeviceName;

注意->被替换为.因为向量元素有Device类型,这不是指针。

您现有的代码与以下向量声明匹配:

vector<Device*> Robot

看到不同。

于 2013-06-09T10:39:09.163 回答