I also have located code that does the same thing when the data are private by using a friend function. I found the friend function on a different online tutorial site.
Is it possible to use the cout statements from the first code example inside the second code example and remove the friend function and existing cout statements from that second code example? When I try I get errors saying the data are private.
you can print out the private members you just can't do it from main. You have to write a method (function inside of the class) that prints out the data and call said method from main.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class complex {
private:
int real;
int img;
public:
complex(int r = 0, int i = 0)
{
real = r;
img = i;
}
void print() { cout << real; }
};
int main() {
complex().print();
}
You can't use private members outside of the class without making the function(s) that use them friend functions. This is by definition. You can, however, define main() to be a friend function (but why? that defeats having private members!).
There is no need to have std::ostream operator<< be a friend as long as the class has public retrieval methods for the real and imaginary components so operator<< can access them:
C++ already uses the complex keyword in the <complex> header, so capitalizing the custom class name as Complex is less likely to produce name collisions. https://en.cppreference.com/w/cpp/numeric/complex
Having accessor methods for real and imag is how the <complex> library manages a complex number.
It is possible to have a std::vector that holds a custom class such as Complex. Overloading std:ostream::operator<< for the vector makes displaying the contents of a vector as simple as displaying a single Complex.