0

こんにちは、私は以下のようなコードを持っていますが、なぜそれが機能しないのかわかりません。

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.
4

2 に答える 2

6

これは、非定数参照が一時オブジェクトにバインドできないためです。const一方、への参照は一時オブジェクトにバインドできます(C++11標準の8.3.5/5を参照)。

于 2013-02-09T16:30:28.130 に答える
2

最初smth2に参照を取得しますが、コンストラクター呼び出しのように一時的なものにバインドすることはできませんa.smth(Claszz2())。ただし、一時参照は変更できないため、 const参照を一時参照にバインドできるため、許可されます。

C ++ 11では、右辺値参照を使用して、一時的なものをバインドすることもできます。

void smth2(Clazz2 &&);

int main()
{
    a.smth(Claszz2()); // calls the rvalue overload
}
于 2013-02-09T16:31:14.523 に答える