通过引用传递变量并构造新对象

Daw*_*ozd 0 c++ reference

你好,我有下面这样的代码,我不知道为什么它不起作用.

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;
}
Run Code Online (Sandbox Code Playgroud)

我有编译错误:

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.
Run Code Online (Sandbox Code Playgroud)

And*_*owl 6

这是因为不允许非常量引用绑定到临时对象.const另一方面,引用可以绑定到临时对象(参见C++ 11标准的8.3.5/5).