Code: Select all
class Foo
{
public:
Foo(int x) {};
};
void ProcessFoo(Foo& foo)
{
}
int main()
{
ProcessFoo(Foo(42));
return 0;
}
Das Kompilieren des Obigen erzeugt Folgendes:
Code: Select all
$ g++ -std=c++11 -c newfile.cpp
newfile.cpp: In function ‘int main()’:
newfile.cpp:23:23: error: invalid initialization of non-const reference of type ‘Foo&’ from an rvalue of type ‘Foo’
ProcessFoo(Foo(42));
^
newfile.cpp:14:6: note: in passing argument 1 of ‘void ProcessFoo(Foo&)’
void ProcessFoo(Foo& foo)
- Erstellen Sie eine temporäre Variable für den Aufruf von ProcessFoo.
Code: Select all
Foo foo42(42);
ProcessFoo(foo42);
- ProcessFoo nimmt eine konstante Referenz: void ProcessFoo(const Foo& foo)
- ProcessFoo lässt Foo einfach als Wert übergeben. void ProcessFoo(Foo foo)