我正在为移动机器人制作一个.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 ++,并且我并不熟练使用指针。
欢迎任何帮助。
答案 0 :(得分:1)
要按索引访问vector<Device> *Robot
元素,请使用以下语法:
(*Robot)[m_device_id]
您的代码应为:
(*Robot)[m_device_id].DeviceName=(string)charDeviceName;
请注意,->
已替换为.
,因为vector元素具有Device
类型,这不是指针。
您现有的代码与以下矢量声明匹配:
vector<Device*> Robot
看到差异。
答案 1 :(得分:1)
Robot是一个指向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
}