Hi,
I'm doing an online C++ quiz thingy, and the code in one the questions is given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
class A{
public:
int v;
A():v(1){}
A(int i):v(i){}
voidoperator&&(int a){v=-v;}
};
int main (void) {
A i = 2;
i && 2;
cout << i << endl;
return 0;
}
It doesn't compile - which is the correct answer in the quiz - but I'm having trouble understanding why it doesn't compile. The error message when attempting to compile is "error: no match for 'operator<<' (operand types are ...". The quiz is largely about overloaded operators, hence the overloaded "&&".
I must be missing something very obvious, but I just don't understand the error message. Any assistance greatly appreciated. Thx!
I don't understand why. I mean it's the && operator which is being overloaded, not the "<<" operator. Surely just because you overload one operator doesn't mean you need to overload every operator. This works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
class A{
public:
int v;
A():v(1){}
A(int i):v(i){}
voidoperator&&(int a){v=-v;}
};
int main (void) {
A i = 2;
i && 2;
// cout << i << endl;
cout << 1+2 << endl;
return 0;
}
... presumably because I'm not trying to output "i", but I don't really see why it's any different.
That is not a proper comparison. You are comparing A to int:
1 2 3 4
A foo;
B bar;
std::cout << foo; // error, no << for A
std::cout << bar.x; // ok, there is << for int
The B fails just like A:
1 2 3 4 5 6 7 8 9
#include <iostream>
class B{
};
int main (void) {
B b;
std::cout << b; // error: no match for 'operator<<'
}
In function 'int main()':
8:13: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'B')
8:13: note: candidates are:
You cannot write std::cout << snafu; unless there is operator<< that accepts typeof(snafu) objects.
The standard library knows how to print an int. But it doesn't know how to print As. A is a user-defined type, and there are no instructions that describe how to print it.
Provide those instructions by defining the function std::ostream &operator<<(std::ostream&, A const&).
#include <iostream>
// There is a record type called A
struct A {};
// It is possible to put objects of type A into C++ streams
// In other words, it is possible to print objects of type A.
std::ostream& operator <<(std::ostream& s, A const& a)
{
return s << "hi, from an object of type A";
}
int main() {
// There is an object of type A called a.
A a;
// Print it by calling the operator<< above
// put the object a to the stream std::cout
std::cout << a;
std::cout << '\n';
}
Oh, I think I see what you mean. Alright, I wasn't familiar with doing that as I guess I've not seen that or needed to do it before. (still an early-learner!!). Yeah, the last two comments make more sense to me, but thanks to all. Much appreciated.