2012-02-21 45 views
2

我得到一个错误约return语句(或CAST)在以下摘录的最终功能从库头“从类型'const myClass'无效转换为类型'int'”,我该如何使它有效?

/////////////////////////////////////////////////////////// 
// class __HashMapDefaultProviderT 

/** 
* @internal 
* @class __HashMapDefaultProviderT 
* @brief This is an implementation of the IHashCodeProviderT interface for the HashMap class. 
* @since 1.0 
*/ 
template<class KeyType> 
class __HashMapDefaultProviderT 
    : public IHashCodeProviderT<KeyType>, 
    public Object 
{ 
public: 

    // Lifecycle 

    /** 
    * This is the default constructor for this class. 
    * 
    * @since  1.0 
    */ 
    __HashMapDefaultProviderT(void) {} 


    /** 
    * This is the destructor for this class. 
    * 
    * @since  1.0 
    */ 
    virtual ~__HashMapDefaultProviderT(void) {} 


    // Operation 

    /** 
    * Gets the hash code of the specified object 
    * 
    * @since  1.0 
    * @return  The hash code of the specified object 
    * @see   Osp::Base::Object::GetHashCode 
    */ 
    int GetHashCode(const KeyType& obj) const 
    { 
     return (int)obj; 
    } 


}; 

的错误是:

无效的转换,从类型“常量myClass'键入'int'

这是什么修复?头文件被称为FBaseColHashMapT.h

我已经添加operator>operator<方法,但我不知道是怎么回事,让我的类散列或如何以允许上面需要投,短继承它,但我想看看我能否避免这种情况。为了支持我写的这两个运营商:

inline int GetHashCode() const {return myIntMember/4 + clientRect.GetHashCode();} 

也许它可能在这里再次使用?

我正在提供myClass作为此模板类的关键字和int作为值。

+0

你想做什么? – 2012-02-21 21:41:40

+1

您正在使用保留的名称。这种架构也看起来像Java,不是很好的C++设计。 – 2012-02-21 21:42:36

+0

@CarlNorum:我试图传递'myClass',它正在慢慢收集成员,但需要保持轻量级,作为参数化模板类的关键。它可以应付继承自'Object'的元素,该元素可以大量定义这个演员阵列,但是我想自己提供演员阵容,这样我就可以避免在更小,更关键性能的类上继承Object。 – John 2012-02-21 21:44:13

回答

7

显然,班级期望KeyType(在你的情况myDescriptor)可以转换为int。因此,解决将是该转换添加到myDescriptor

class myDescriptor 
{ 
public: 
    operator int() const { return (whatever the library expects, probably a hash key); } 
    // ... 
}; 
+0

'return GetHashCode();' – 2012-02-21 21:45:34

+0

只是简单的说明'const'在这里真的很重要!我把它留在我的代码中,无法弄清楚GCC为什么仍在抱怨。 – 2013-07-30 21:44:39

2

无论你的类需要提供一个转换为int:

myClass::operator int() const { 
    return myIntMember/4 + clientRect.GetHashCode(); 
} 

...或者你需要专注HashMap类的GetHashCode()成员功能(你会做这个MyClass中的头球,但在HashMap中的命名空间):

template<class KeyType> 
inline int __HashMapDefaultProviderT::GetHashCode(const myClass& obj) const { 
    return obj.myIntMember/4 + obj.clientRect.GetHashCode(); 
} 

我不熟悉的bada,这样我就可以”说哪个是预期的方法。不过,这两种都有些诡异。