about c++ conversion : no known conversion for argument 1 from ‘[some_class]' to ‘[some_class]&’

后端 未结 2 1581
一个人的身影
一个人的身影 2021-02-01 01:31

I\'m working on C++, and had an error that I didn\'t know the exact reason. I\'ve found the solution, but still want to know why.

    class Base
    {
        p         


        
2条回答
  •  猫巷女王i
    2021-02-01 02:05

    You are passing a temporary Base object here:

    b.something(Base());
    

    but you try to bind that to a non-const lvalue reference here:

    void something(Base& b){}
    

    This is not allowed in standard C++. You need a const reference.

    void something(const Base& b){}
    

    When you do this:

    Base c;
    b.something(c);
    

    you are not passing a temporary. The non-const reference binds to c.

提交回复
热议问题