I have the following piece of code. I'm trying to print the sum of two objects ints but the compiler gives me the following error:
binary '<<' : No operator found which takes a right-hand operand of type 'B' (or there is no acceptable conversion)
I don't really understand what the error means. Why does it say the operator << needs a type 'B'. Isn't there a sum of two ints?
#include <iostream>
using namespace std;
class A
{
protected:
int x;
public:
A(int i) :x(i) {}
int get_x() {
return x;
}
};
class B : public A
{
public:
B(int i) :A(i) {}
B operator+(const B& b) const {
return x + b.x;
}
};
int main()
{
const B a(22), b(-12);
cout << a + b;
system("Pause");
}
The a + b
expression is using your custom operator - so it's as if you'd written (module constness - I'm just trying to get the flavour of what's going on):
B c = a + b;
cout << c;
That doesn't work because the compiler can't find a suitable <<
operator with a B
as the right operand - just as the error message says. It's worth asking yourself what you expected it to do with that.
If you want to print the value of x
in the result, perhaps you want:
cout << (a + b).get_x();
Just overload the << operator:
std::ostream& operator<<(std::ostream& out, const B& b)
{
return out << b.x;
}
Add an operator <<
definition to your B
class. Something like
class B : public A {
public: B(int i) : A(i) {}
B operator +(const B & b) const { return x + b.x; }
friend std::ostream & operator <<(std::ostream & out, const B & obj) {
out << obj.x;
return out;
}
};
Can be done like this:
#include<iostream>
using namespace std;
class A
{
protected: int x;
public: A(int i) :x(i) {}
int get_x() { return x; }
};
class B : public A
{
public: B(int i) :A(i) {}
B operator+(const B& b) const { return x + b.x; }
};
ostream & operator << (ostream &object,B &data)
{
object << data.get_x();
return object;
}
int main()
{
const B a(22), b(-12);
cout << (a + b);
system("Pause");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.