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

时间:2013-02-09 16:29:19

标签: 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;
}

我有编译错误:

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.

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

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

在C ++ 11中,您可以使用 rvalue-refrerence ,这样您就可以绑定临时对象了:

void smth2(Clazz2 &&);

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