So far, we have learned how to write lambdas in C++. All the examples use lambda expressions outside classes, either as variables or as part of the main() function. However, most of our C++ code lives in classes. This begs the question—how can we use lambdas in classes?
To explore this question, we need an example of a simple class. Let's use a class that represents basic imaginary numbers:
class ImaginaryNumber{
private:
int real;
int imaginary;
public:
ImaginaryNumber() : real(0), imaginary(0){};
ImaginaryNumber(int real, int imaginary) : real(real),
imaginary(imaginary){};
};
We want to use our new-found lambda superpowers to write a simple toString function, as shown in the following code:
string toString(){
return to_string(real) + " + " + to_string(imaginary) + "i";
}
So, what...