2

我正在从事从 VC6 到 VC9 的迁移项目。在 VC9 (Visual Studio 2008) 中,我在将 const 成员传递给接受引用的方法时遇到编译错误。它在 VC6 中编译时没有错误。

示例程序:

class A
{
};

typedef CList<A, A&> CAlist;

class B
{
    CAlist m_Alist;

public:
    const B& operator=( const B& Src);
};

const B& B::operator=( const B& Src)
{
    POSITION pos = Src.m_Alist.GetHeadPosition();

    while( pos != NULL)
    {
        **m_Alist.AddTail( Src.m_Alist.GetNext(pos) );**
    }

    return *this;
}

错误:在编译上面的程序时,我得到了错误

错误 C2664:“POSITION CList::AddTail(ARG_TYPE)”:无法将参数 1 从“const A”转换为“A &”

请帮我解决这个错误。

4

1 回答 1

1

那是因为该GetNext()方法返回一个类的临时对象,A而该函数AddTail采用参数A&。由于临时对象不能绑定到非常量引用,因此您会收到错误消息。解决它的最简单方法是将其分成两个语句。例如:

    while( pos != NULL)
    {
        A a =  Src.m_Alist.GetNext(pos);
        m_Alist.AddTail(a);
    }
于 2010-08-20T10:31:20.567 回答