开发者

How to resolve compilation error "cannot convert const to reference" in VC++9

I am working in migration project from VC6 to VC9. In VC9 (Visual Studio 2008), I got compilation error while passing cons开发者_运维百科t member to a method which is accepting reference. It is getting compiled without error in VC6.

Sample Program:

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;
}

Error: Whiling compiling above program, I got error as

error C2664: 'POSITION CList::AddTail(ARG_TYPE)' : cannot convert parameter 1 from 'const A' to 'A &'

Please help me to resolve this error.


That is because the GetNext() method returns a temoprary object of class A and the function AddTail takes the parameter A&. Since a temporary object can not be bound to a non-const reference you get the error. The simplest way to solve it is to break it into two statements. For example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜