#include <linux/input.h>
#include <string.h>
#include <gtest/gtest.h>
#include <string>
class Parent{
public:
Parent(){
}
virtual std::string GetString()
{
int amount = 1;
input_event ev[amount];
/**
* This solves the problem
*/
memset(ev, 0, sizeof(ev[0]));
ev[0].code = BTN_9;
ev[0].value = 1;
char* temp = reinterpret_cast<char*>(ev);
std::string msg(temp, sizeof(ev[0]) * amount);
return msg;
}
};
class Child : public Parent
{
public:
Child(){
}
virtual std::string GetString()
{
int amount = 1;
input_event ev[amount];
ev[0].code = BTN_9;
ev[0].value = 1;
char* temp = reinterpret_cast<char*>(ev);
std::string msg(temp, sizeof(ev[0]) * amount);
return msg;
}
};
class Child2 : public Parent
{
public:
Child2(){
}
virtual std::string GetString()
{
std::string temp(Parent::GetString());
return temp;
}
};
TEST(CastToString, test)
{
Parent parent = Parent();
Child child1 = Child();
Child2 child2 = Child2();
std::string pString(parent.GetString());
std::string c1String(child1.GetString());
std::string c2String(child2.GetString());
EXPECT_EQ(pString, c1String);
EXPECT_EQ(pString, c2String);
}
我只是复制了整个样本。问题在于 Child2s GetString 函数的调用。它总是返回不同的值,因此我假设存在一些分配问题,但我无法弄清楚。