I create the class 'Point', overload the operator '+' between 2 Point object and the operator '<<' to show the Point object. I can't compile and run the code.
The error is that there is no operator "<<" matched. This is occured to "cout << "p3: " << (p1+p2) << endl;"
class Point {
public:
Point(int x=0, int y=0) : _x(x), _y(y) {};
Point operator +(Point &p);
int getX() {
return _x;
}
int getY() {
return _y;
}
friend ostream& operator <<(ostream& out, Point &p);
private:
int _x, _y;
};
Point Point::operator +(Point &p) {
Point np(this->_x+p.getX(), this->_y+p.getY());
return np;
}
ostream& operator <<(ostream &out, Point &p) {
out << '(' << p._x << ',' << p._y << ')';
return out;
}
int main() {
Point p1(1, 2);
Point p2;
cout << "p1: " << p1 << endl;
cout << "p2: " << p2 << endl;
cout << "p3: " << (p1+p2) << endl;
system("pause");
return 0;
}
The expression
(p1+p2)
is an rvalue. The function
ostream& operator <<(ostream &out, Point &p)
expects a reference to Point. You can't pass an rvalue to this function. Change it to
ostream& operator <<(ostream &out, const Point &p)
in the declaration and the definition.
C++ only allows a temporary to be passed to a const reference. See this: How come a non-const reference cannot bind to a temporary object?
Modify a temporary is meaningless. You need to define a const reference to promise you won't modify it and extend its lifetime.
When overloading operators, const correctness is not optional. The following prototypes are what you require...
Point operator + (const Point &p) const;
friend ostream& operator <<(ostream& out, const Point &p);
Related
Suppose there is a cPoint class.
class cPoint {
int x, y, z;
};
I wanted to print all of three variables in a single statement. So, I overloaded operator << just like
friend std::ostream& operator<< (std::ostream &cout, cPoint &p);
std::ostream& operator<< (std::ostream &out, cPoint &p) {
out << p.get_x() << " " << p.get_y() << " " << p.get_z() << std::endl;
return out;
}
Make sense?
My question lies in the lines of that what would happen in case of insertion operator(>>). I overloaded that as well to take the values of x, y and z into a single statement.
friend std::istream& operator>> (std::istream &cin, Point &p);
std::istream& operator>> (std::istream &in, Point &p) {
int tmp;
in >> tmp;
p.set_x(tmp);
in >> tmp;
p.set_y(tmp);
in >> tmp;
p.set_z(tmp);
}
Clear?
int main() {
cout << p << endl;
cin >> p;
}
I know that if operator<< returned void then the compiler evaluates cout << p << endl;
Due to the precedence/associativity rules, it evaluates this expression as (cout << cPoint) << endl;. cout << cPoint calls our void-returning overloaded operator<< function, which returns void. Then the partially evaluated expression becomes: void << endl;, which makes no sense!
But what would happen in case of >>. Why can't I return a void for >> as like:
void operator>> (std::istream &cin, Point &p);
Because it does not matter if cin >> p returns void or something else. There is no other operand who could use it. This is not clear.
You can return void from stream extracting operator >>, just like you can return void from a stream inserting operator <<. And just like with the inserting one, it will prevent you from doing chaining:
cPoint p, q;
cin >> p >> q; // This would fail with return type void
... and the very common test-correctness idiom:
cPoint p;
if (cin >> p) {
}
I overloaded operator << just like ...
Proper override should take the second parameter by const reference:
friend std::ostream& operator<< (std::ostream &cout, const cPoint &p);
// ^^^^^
I overloaded that as well to take the values of x, y and z into a single statement.
You forgot to return in from the implementation:
std::istream& operator>> (std::istream &in, Point &p) {
int tmp;
in >> tmp;
p.set_x(tmp);
in >> tmp;
p.set_y(tmp);
in >> tmp;
p.set_z(tmp);
return in; <<== Here
}
Making it void would prevent you from reading anything else after the point on the same line.
I'm a student learning c++. today, I was making a operator overload function to use it in 'cout'. following is a class that contains name, coordinates, etc.
class Custom {
public:
string name;
int x;
int y;
Custom(string _name, int x, int y):name(_name){
this->x = x;
this->y = y;
}
int getDis() const {
return static_cast<int>(sqrt(x*x+y*y));
}
friend ostream& operator << (ostream& os, const Custom& other);
};
ostream& operator << (ostream& os, const Custom& other){
cout << this->name << " : " << getDis() << endl;; // error
return os;
}
However, this code isn't working because of 'THIS' keyword that I was expecting it points to the object. I want to show the object's name and distance value. How can I solve it? I think it is similar with Java's toString method so that it will be able to get THIS.
Thanks in advance for your answer and sorry for poor english. If you don't understand my question don't hesitate to make a comment.
this is available only in member functions, but your operator<< is not a class member (declaring it as friend does not make it a member). It is a global function, as it should be. In a global function, just use the arguments you are passing in:
ostream& operator << (ostream& os, const Custom& other)
{
os << other.name << " : " << other.getDis() << endl;
return os;
}
Also note os replaced cout in the code above. Using cout was an error - the output operator should output to the provided stream, not to cout always.
I'm working in a Big Integer implementation in C++ and I'm trying to use cout with my BigInt class. I already overloaded the << operator but it doesn't work in some cases.
Here is my code:
inline std::ostream& operator << (ostream &stream, BigInt &B){
if (!B.getSign()){
stream << '-';
}
stream << B.getNumber();
return stream;
}
The code above works with:
c = a + b;
cout << c << endl;
But fails with:
cout << a + b << endl;
In the first case the program runs fine, but in the second the compiler gave an error:
main.cc: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
It's possible to overload the << operator for function in both cases?
Methods:
string getNumber ();
bool getSign ();
string BigInt::getNumber (){
return this->number;
}
bool BigInt::getSign (){
return this->sign;
}
As chris already pointed out in comments very quickly (as usual), you have a temporary created in here:
cout << a + b << endl;
You cannot bind that to a non-const reference. You will need to change the signature of your operator overloading by adding the const keyword to the reference.
This code works for me with a dummy BigInt implementation (as you have not shared yours):
#include <iostream>
using namespace std;
class BigInt
{
public:
bool getSign() const { return true; }
int getNumber() const { return 0; }
const BigInt operator+(const BigInt &other) const {}
};
inline std::ostream& operator << (ostream &stream, const BigInt &B){
// ^^^^^
if (!B.getSign()){
stream << '-';
}
stream << B.getNumber();
return stream;
}
int main()
{
BigInt a, b, c;
c = a + b;
cout << c << endl;
cout << a + b << endl;
return 0;
}
But yeah, I agree that the error message is not self-explanatory in this particular case.
Change
inline std::ostream& operator << (ostream &stream, BigInt &B){
to
inline std::ostream& operator << (ostream &stream, BigInt const& B){
c can be a used where BiInt& is expected but a+b cannot be because a+b is a temporary. But it can be used where BigInt const& is expected.
I'm a C++ beginner, trying to learn from online videos. In of the operator overloading examples in the lectures the following code is there and gives the error
error: no match for 'operator<<' in 'std::cout << operator+(((point&)(& p1)), ((point&)(& p2)))'compilation terminated due to -Wfatal-errors.
on the line marked with comment. Can someone please tell what's wrong in the code? I am just trying what the professor explained in the lecture but can't compile.
===============
#include <iostream>
using namespace std;
class point{
public:
double x,y;
};
point operator+ (point& p1, point& p2)
{
point sum = {p1.x + p2.x, p1.y + p2.y};
return sum;
}
ostream& operator<< (ostream& out, point& p)
{
out << "("<<p.x<<","<<p.y<<")";
return out;
}
int main(int argc, const char * argv[])
{
point p1 = {2,3};
point p2 = {2,3};
point p3;
cout << p1 << p2;
cout << p1+p2; // gives a compliation error
return 0;
}
It's just a problem with const correctness. Your operator+ returns a temporary, so you can't bind a non-const reference to it when calling operator<<. Make the signature:
ostream& operator<< (ostream& out, const point& p)
While you don't need to do it to fix this compilation error, you won't be able to add const points unless you fix the operator+ similarly:
point operator+(const point& p1, const point& p2)
Change the parameter type from point& to const point& for operator+ and operator<<. Non-const reference cannot bind to a temporary (which is returned by operator+) and that is causing the compile error.
The reason is the second parameter should be a const reference. (you don't want it gets modified, right?) So, it is like,
std::ostream& operator<< (std::ostream &out, const Point &p)
{
out << "(" << p.x << ", " << p.y << ")";
return out;
}
I have a polynomial implementation in a linked list and want to do std::ostream overloading operation but it gives my an error that no match for ‘operator<<’ in ‘std::cout << p5’
That's my implementation but when I test it through cout << p5 I get the aforementioned error.
UPDATE:
header file:
struct term{
double coef;
unsigned deg;
struct term * next;
};
class Polynomial {
public:
constructors etc
overloading functions
friend ostream& operator << (ostream& out,const term& object);
}
then in other file poly.cpp i have:
ostream & operator << (ostream& out, const Polynomial object){
term* q = object.getptr();
if (object.getptr() == NULL)
out << "( )";
else
while(q != NULL)
{
out << q->coef << "x^" << q->deg << " ";
q = q->next;
}
return out;
}
in main.cpp
Polynomial p5, then added some terms and cout << p5 but I get errors.
I think it's your declarations which are causing the problem:
friend ostream & operator << (ostream & out, const term & object);
and
ostream & operator << (ostream & out, const Polynomial & object);
These don't match. One is using a term object and the latter is using a Polynomial object. I'm assuming you want this function to use a term object because the function uses data memebers specific to the struct term. So change the latter to accept a term object:
ostream & operator << (ostream & out, const term & object);