Passing variables by reference and construct new objects

♀尐吖头ヾ 提交于 2019-12-31 05:08:06

问题


Hello there i have code like this one below and i don't know why it doesn't work.

class Clazz2;
class Clazz
{
    public:
    void smth(Clazz2& c)
    {

    }

    void smth2(const Clazz2& c)
    {

    }
};

class Clazz2
{
    int a,b;
};

int main()
{
    Clazz a;
    Clazz2 z;
    a.smth(z);
    //a.smth(Clazz2()); //<-- this doesn't work
    a.smth2(Clazz2()); // <-- this is ok
    return 0;
}

I have compilation error:

g++ -Wall -c "test.cpp" (in directory: /home/asdf/Desktop/tmp)
test.cpp: In function ‘int main()’:
test.cpp:26:17: error: no matching function for call to ‘Clazz::smth(Clazz2)’
test.cpp:26:17: note: candidate is:
test.cpp:5:7: note: void Clazz::smth(Clazz2&)
test.cpp:5:7: note:   no known conversion for argument 1 from ‘Clazz2’ to ‘Clazz2&’
Compilation failed.

回答1:


This is because non-constant references are not allowed to bind to temporary objects. References to const, on the other hand, can bind to temporary objects (see 8.3.5/5 of the C++11 Standard).




回答2:


Your first smth2 takes a reference, which cannot be bound to a temporary like your constructor call a.smth(Claszz2()). However, a const reference can be bound to a temporary because we cannot modify the temporary, so it is allowed.

In C++11, you can use an rvalue-refrerence so that you have the ability to bind temporaries as well:

void smth2(Clazz2 &&);

int main()
{
    a.smth(Claszz2()); // calls the rvalue overload
}


来源:https://stackoverflow.com/questions/14790148/passing-variables-by-reference-and-construct-new-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!