Hi, I am imitating a queue using a linked list. I created a struct node, then I created a struct called imiQueue with some member functions and the imiQueue functions like a partially complete queue. However, when I use the ? ternary operator along with cout, it doesn't work, but using if & else does.
(if you need to run the program, enter 1 and the number you want to insert to add to the queue, enter 0 to pop out (the problematic part), and -1 to exit)
Can anyone tell me why
at line 66, (my entire code is below)
1 2 3 4 5
elseif (q1==0) {
newQueue.isEmpty() ?
newQueue.pop_out() :
cout << "popped out element w/ value " << newQueue.pop_out() << endl;
}
returns error
" error: invalid user-defined conversion from 'std::basic_ostream<char>::__ostream_type {aka std::basic_ostream<char>}' to 'int' [-fpermissive]|"
even though the return type of newQueue.pop_out() returns an integer
but
1 2 3 4 5
elseif (q1==0) {
if (newQueue.isEmpty()) {
newQueue.pop_out()}
else {
cout << "popped out element w/ value " << newQueue.pop_out() << endl; }
The expression A ? B : C is an expression, not an statement like if(A) B else C;
As any expression its goal in life is to produce a value. You can write X = A ? B : C; and it will copy B into X if A is true, and it will copy C into X if A is false.
As any expression it also has a type, because C++ is a statically-typed language, that type must be known at compile time. If the types of B and C are the same, it's easy: the type of A?B:C is that type. If the types differ, A?B:C must find a common type to which both B and C can implicitly convert to.
Now in your case:
B is newQueue.pop_out() and its type is int
C is cout << "popped out element w/ value " << newQueue.pop_out() << endl; and its type is std::ostream
There is no way to convert ostream and int to the same common type, and that's what the compiler told you (in a slightly odd way, compare to current messages from
clang "incompatible operand types ('int' and 'basic_ostream<char, std::__1::char_traits<char> >')")
and gcc " error: operands to ?: have different types 'int' and 'std::basic_ostream<char>'"