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

Passing variables by reference and construct new objects

本文关键字:新对象 对象 引用 变量      更新时间:2023-10-16

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

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

我有编译错误:

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.

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

您的第一个smth2接受一个引用,该引用不能绑定到像您的构造函数调用a.smth(Claszz2())那样的临时引用。但是,const引用可以绑定到临时引用,因为我们不能修改临时引用,所以它是允许的。

在C++11中,您可以使用右值参考,这样您就可以同时绑定临时值:

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