在对自定义类 Elevator 的 std::vector 进行排序后,我遇到了问题。
类定义:
class Elevator
{
private:
uint16_t m_id;
char *m_channel;
ElevatorType m_type;
public:
Elevator(uint16_t id, const char *channel, ElevatorType type);
Elevator(const Elevator &other);
~Elevator();
char *ToCString();
bool operator<(const Elevator& rhs) const;
static vector<Elevator> *ElevatorsFromWorkbook(const char *path);
};
less 运算符是这样实现的:
bool Elevator::operator<(const Elevator& rhs) const
{
return (this->m_id < rhs.m_id);
}
ToCString方法是这样实现的:
char *Elevator::ToCString()
{
char *output = (char*)malloc(sizeof(char) * (8+strlen(m_channel)));
char type = 'U';
if (m_type == ELEVATOR_TYPE_A)
{
type = 'A';
}
else if (m_type == ELEVATOR_TYPE_G)
{
type = 'G';
}
else if (m_type == ELEVATOR_TYPE_M)
{
type = 'M';
}
sprintf(output,"%d %s %c",m_id,m_channel,type);
return output;
}
复制构造函数:
Elevator::Elevator(const Elevator &other)
{
m_id = other.m_id;
m_channel = (char*)malloc(sizeof(char)*(strlen(other.m_channel)+1));
strcpy(m_channel,other.m_channel);
m_type = other.m_type;
}
问题示例:
std::vector<Elevator> elevators;
elevators.push_back(Elevator(4569,"CHANNEL3",ELEVATOR_TYPE_G));
elevators.push_back(Elevator(4567,"CHANNEL3",ELEVATOR_TYPE_G));
printf("%s\n",elevators.at(0).ToCString()); //Prints "4567 CHANNEL1 G"
std::sort(elevators.begin(),elevators.end());
printf("%s\n",elevators.at(0).ToCString()); //ISSUE: Prints "4567 4567 ▒#a G"
我究竟做错了什么?谢谢你的时间!
编译注意事项:我正在使用带有这些标志的 Cygwin:-Wall -Wextra -fno-exceptions -fno-rtti -march=pentium4 -O2 -fomit-frame-pointer -pipe