2012-09-12 39 views
0
#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函数的调用。 它总是返回不同的值,因此我认为,有一些分配问题,但我无法弄清楚。父母的调用虚函数

+0

什么是ev定义? –

+0

尽可能尝试使用编辑器和浏览器的复制和粘贴功能。目前形式的代码无法编译。 – hvd

+0

@ hvd你为什么这么说? – john

回答

3

我认为错误是在这里

std::string msg(temp, sizeof(ev) * amount); 

应该

std::string msg(temp, sizeof(ev[0]) * amount); 

(两地)。

由于数组大小错误,您的字符串中会有额外的垃圾字节,所以它们没有相等的比较结果。

+0

改变了,但没有帮助。 –

+1

嗯,我建议你改变你的两个功能的内容为理智的东西,如'std :: string msg(“testing”);返回味精;'。这将帮助您缩小问题范围。或者你可以使用调试器。 – john

+0

理智的问题是,我将问题的范围缩小到了这个范围。不知何故,铸造是它的原因。调试器向我展示了两个不同的字符串,在函数中,真的不知道如何处理它,认为这是一个基本问题。 –