我是新来的堆栈溢出和C++!这就是问题所在:
目标是使用下一个接口创建容器类:
IContainer.h.h:
class ElemNotFound {};
template < class ElemType, class IndexType > class IContainer
{
public:
virtual const ElemType& GetElem(const IndexType& index) const throw (ElemNotFound) = 0;
virtual void PutElem(const IndexType& index, const ElemType& elem) throw () = 0;
};
使用该接口的当前代码是:
#include "IContainer.h"
#include <vector>
class Container : public IContainer < class ElemType, class IndexType >
{
private:
struct ContainerElement
{
IndexType& Index;
ElemType& Data;
};
std::vector < ContainerElement > MyVector;
std::vector < ContainerElement > ::iterator MyIterator;
public:
// EDIT: that operator== part is incorrect as
// failed attempt to circumvent inability to compare custom types
friend bool operator== (IndexType& x, const IndexType& y)
{
if (x == y) return 1;
else return 0;
}
const ElemType& GetElem(const IndexType& index)
{
try
{
MyIterator = MyVector.begin();
while (MyIterator != MyVector.end())
{
if (MyIterator->Index == index)
// PROBLEM: missing operator "==" for IndexType == const IndexType
{
// do useful things
}
MyIterator++;
}
}
catch (Exception e) // everything down below is a placeholder
{
throw (ElemNotFound) = 0;
}
}
void PutElem(const IndexType& index, const ElemType& elem)
{
}
};
直接比较IndexType和const IndexType (使用"==")并不是因为我不知道的原因。我希望比较向量中的自定义索引和函数中用于从容器中获取元素的索引。对自定义类型使用操作符重载"==“也不起作用。如果是不正确的继承或错误使用操作符过载-我不知道!
所以问题是:如何比较使用模板的类中的const和non自定义类型变量?
发布于 2015-07-12 05:49:25
您的代码存在一个根本问题;您看到的所有其他错误都只隐藏了真正的错误。这句话是:
class Container : public IContainer < class ElemType, class IndexType >
class ElemType
和class IndexType
的论点具有误导性。这些实际上是从未定义过的类的转发声明。它们的名称与IContainer
的模板参数名称相同,这只是一个巧合。
换句话说:您正在用不完整的类实例化模板。
这意味着编译器对它们几乎一无所知。他们有公共建设者吗?他们支持operator==
吗?
考虑一下这个非常简化的程序版本:
template < class ElemType, class IndexType > class IContainer
{
public:
virtual void PutElem(const IndexType& index, const ElemType& elem);
};
class Container : public IContainer < class ElemType, class IndexType >
{
public:
void PutElem(const IndexType& index, const ElemType& elem)
{
bool b1 = index == index;
bool b2 = elem == elem;
}
};
int main()
{
Container c;
}
编译错误(取决于编译器):
stackoverflow.cpp(12) : error C2676: binary '==' : 'const IndexType' does not define this operator or a conversion to a type acceptable to the predefined operator
stackoverflow.cpp(13) : error C2676: binary '==' : 'const ElemType' does not define this operator or a conversion to a type acceptable to the predefined operator
有了它:类是未定义的,编译器甚至不知道它们是否支持==
。
进一步的问题:
Container
的GetElem
显然应该覆盖基类中的GetElem
,但它是const
。重写区分了const
和非const
。MyIterator = MyVector.begin();
行不能在const
函数中工作,因为MyIterator
被修改了(而不是mutable
)。int
这样的基本类型,因为如果两个操作数都是原语类型,则不能重载operator==
。我不完全确定您的代码的真正意图是什么,但也许您希望Container
也成为一个模板,用于生成Container
类?
你可以这样做:
template < class ElemType, class IndexType >
class Container : public IContainer < ElemType, IndexType >
这是起点;然后您可以单独修复所有其他错误。请随时为他们问个别问题。
https://stackoverflow.com/questions/31368011
复制