【发布时间】:2015-02-11 11:23:59
【问题描述】:
所以,这是我的问题:我想创建一个类,根据它的参数,它可以与 == 与内部枚举值进行比较。所以这就是我尝试过的:
class Type
{
public:
enum T_values {VALUE,
OTHERVALUE
};
Type(T_values value) : m_value(value) {}
bool operator==(T_values& value) {return (value == m_value);}
private:
T_values m_value;
};
struct foo
{
foo(Type TYPE) : m_Ts(1, std::vector<Type*>(1, &TYPE)) {}
std::vector<std::vector<Type*>> m_Ts;
void bar(int, int);
};
void foo::bar(int i, int j)
{
if(*m_Ts[i][j] == Type::VALUE)
{ cout<<"it works"; }
}
int main()
{
Type TYPE(Type::VALUE);
foo test(TYPE);
test.bar(0,0);
return 0;
}
然后,我有一个漂亮而清晰的编译错误:
...\workspace\main.cpp|29|error: no match for 'operator==' in '*(&((foo*)this)->foo::m_Ts.std::vector<_Tp, _Alloc>::operator[]<std::vector<Type*>, std::allocator<std::vector<Type*> > >(((std::vector<std::vector<Type*> >::size_type)i)))->std::vector<_Tp, _Alloc>::operator[]<Type*, std::allocator<Type*> >(((std::vector<Type*>::size_type)j)) == (Type::T_values)0u'|
而且……我不知道。有什么想法吗?
【问题讨论】:
-
修复编译错误后实际上会遇到更严重的问题,即undefined behavior,因为在向量的向量中会有一个杂散的指针。原因是您将参数
TYPE传递给foo构造函数按值。
标签: c++ class pointers enums operator-overloading