如何在VC ++ 9中解决编译错误“无法将const转换为引用”

时间:2010-08-20 10:13:53

标签: c++ compiler-errors visual-c++-2008

我正在从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;
}

错误: Whiling编译上面的程序,我得到错误

  

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

请帮我解决此错误。

1 个答案:

答案 0 :(得分:1)

这是因为GetNext()方法返回类A的临时对象,函数AddTail采用参数A&。由于临时对象无法绑定到非const引用,因此会出现错误。解决它的最简单方法是将其分解为两个语句。例如:

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