【问题标题】:no match for operator== with 2D vector, enums and pointersoperator== 与 2D 向量、枚举和指针不匹配
【发布时间】: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


【解决方案1】:

制作这条线:

bool operator==(T_values& value) {return (value == m_value);}

进入这个:

                    //  v-- no reference
bool operator==(T_values value) {return (value == m_value);}

您不能通过引用获取文字 Type::VALUE,因为它不是对象。

【讨论】:

  • "您不能通过引用获取文字 Type::VALUE,因为它不是对象。"这就是为什么您通过 const 引用来获取它的原因 :-)
  • 有区别吗?我猜一个指向枚举类型的指针并不比类型本身小..
  • 在这里使用 const 或 rvalue 引用没有意义,不。只是按价值传递,这是我的建议。我会(通常)对所有原始类型做同样的事情,除了在函数模板中我不会引入重载只是为了区别对待它们。
【解决方案2】:

这行也有问题。

foo(Type TYPE) :  m_Ts(1, std::vector<Type*>(1, &TYPE)) {}

您正在存储临时对象的地址。函数返回时该地址无效。

【讨论】:

  • 是的,我已经注意到了,但这是为了举例。在实际代码中,我有一个用 nullptr 填充的 vector2d,我使用 new 在其中添加了一些东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多