0

抱歉,没有示例,所以我们必须在这里查看真实代码。发生的事情是,我有课CItemElem(注意这是一个旧的来源,请不要考虑匈牙利符号、类名等)。如下例所示,我正在尝试做同样的事情CItemElem

class A
{
public:
    int value;
};

int _tmain( int argc, _TCHAR* argv[] )
{
    std::vector<A> hold;
    A a;
    hold.push_back(a);
}

尽管CItemElem编译器在尝试使用类时给了我 C2679

vector<CItemElem>hold; CItemElem item; hold.push_back(item);

Error C2679: '=' binary :no operator found which takes a right-hand operand of type 'const CItemElem' (or there is no acceptable conversion)

通过单击错误,它会将我带到*_First = _Val; 此功能上的这一行xutility

template<class _FwdIt,
    class _Ty> inline
    void fill(_FwdIt _First, _FwdIt _Last, const _Ty& _Val)
    {   // copy _Val through [_First, _Last)
    for (; _First != _Last; ++_First)
        *_First = _Val;
    }

CItemElem 类太长且派生,因此我决定将其上传到 pastebin,而不是在这里粘贴大量代码。 Pastebin:类 CItemElem 标题 (item.h)

请注意,CItemElem 派生自 CItemBase 并且重载了 = 运算符,它也通过 CItemBase = 运算符。这是来自item.cpp

CItemElem& CItemElem::operator =( CItemElem & ie )
{
    CItemBase::operator =( ie );
4

2 回答 2

3

看起来好像没有=CItemElem. STL 容器(例如vector)期望它们包含的内容具有某些属性,包括赋值运算符。如果可以修改类,可以加一个:

class CItemElem
{
...
public:

  CItemElem & operator=(const CItemElem &other)
  {
    // copy whatever must be copied
    x = other.x;

    return *this;
  }
}

编辑:
我现在看到标题包含赋值运算符的声明:

virtual CItemElem&      operator = ( CItemElem & ie );

但签名是错误的——它不见了const。如果您可以更改它(在声明和定义中),它应该可以工作。

编辑:
如果你不能编辑基类,你有几个选择。可能最安全的方法是将代码从复制CItemBase::operator=CItemElem::operator=. 不漂亮,但那是原作者的错;争论应该一直存在const &

于 2012-09-01T15:32:17.750 回答
2

CItemElem 有operator=(CItemElem&). 此函数不能接受const参数(正如编译器准确告诉您的那样)并且不符合std::vector作为元素类型的要求。不可能在std::vector.

于 2012-09-01T15:28:12.867 回答