The problem is that the member function of the front
class returns a reference of type Deb &
to a queue element of type std::queue<Deb>
. However, the operator operator <<
not defined for the stream std::ostream
and the object of the Deb
structure. Therefore, the compiler does not know what to do in this case, and gives an error message.
The easiest way to get around the problem is to first create an object based on the returned reference from the member function of the front
class, and then output the members of this object to the console, since they are declared public access control (default for structures).
For example,
#include <iostream> #include <queue> struct Deb { int age; char FIO[20]; char group[20]; }; int main() { std::queue<Deb> chek; Deb deb1 = { 20, "Maks Boll", "C++" }; chek.push( deb1 ); Deb deb2 = chek.front(); std::cout << "age: " << deb2.age << ", FIO: " << deb2.FIO << ", group: " << deb2.group << '\n'; }
The output of the program to the console:
age: 20, FIO: Maks Boll, group: C++
If you are using a compiler that supports C ++ 17, then you can use a so-called structured binding declaration .
Below is a demo program that shows how you can use this declaration to output structure elements to the console.
#include <iostream> #include <queue> struct Deb { int age; char FIO[20]; char group[20]; }; int main() { std::queue<Deb> chek; Deb deb = { 20,"Maks Boll", "C++" }; chek.push( deb ); const auto [ age, FIO, group] = chek.front(); std::cout << "age: " << age << ", FIO: " << FIO << ", group: " << group << '\n'; }
The output of the program:
age: 20, FIO: Maks Boll, group: C++
By the way, C ++ 17 also defines a generic std;:size
function that can be used with standard containers and arrays. Therefore you can also write
#include <utility> // ... std::cout << " " << std::size( chek ) << '\n';
instead
cout << " " << chek.size() << endl;
making programs more flexible and resistant to change.
Otherwise, if the compiler does not support the C ++ 17 standard, you should independently define such an operator. For example, it might look like this.
std::ostream & operator <<( std::ostream &os, const Deb &deb ) { return os << "age: " << deb.age << ", FIO: " << deb.FIO << ", group: " << deb.group; }
Below is the corresponding demonstration program.
#include <iostream> #include <queue> struct Deb { int age; char FIO[20]; char group[20]; }; std::ostream & operator <<( std::ostream &os, const Deb &deb ) { return os << "age: " << deb.age << ", FIO: " << deb.FIO << ", group: " << deb.group; } int main() { std::queue<Deb> chek; Deb deb = { 20,"Maks Boll", "C++" }; chek.push( deb ); std::cout << chek.front() << '\n';; }
Its output to the console is identical to the output shown for the previous demo program:
age: 20, FIO: Maks Boll, group: C++
front()
function cannot output anything. The operator must output<<
. Why do you expect this to work? How can the operator<<
know how to display your structure? - AnT