Cannot overload the >> operator with istream c++ - c++

I am trying to overload the >> operator to use it like cin with my class. Here is the code:
class Base {
public:
int mx;
Base() {}
Base(int x) : mx(x) {}
friend std::istream &operator>>(std::istream &, Base &);
friend std::ostream &operator<<(std::ostream &, const Base &);
};
std::istream &operator >>(std::istream &in, Base &object) {
in >> object.mx;
return in;
}
std::ostream &operator <<(std::ostream &out, const Base &object) {
out << object.mx;
return out;
}
int main() {
Base test();
std::cin >> test;
std::cout << test;
system("PAUSE");
return 0;
}
When I try to compile I get "error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'Base (__cdecl *)(void)' (or there is no acceptable conversion)"
and Intellisense says no operator '>>' matches these operands.
the ostream version doesn't seem to have any problem.
Why?

Your code has two problems.
1) This declares a function instead of defining variable:
Base test();
Make that:
Base test;
2) You need to take a reference for the second parameter of operator>>:
std::istream &operator >>(std::istream &in, Base& object)
Also, your code does not really work for operator<<, at least it won't do what you are expecting it to do unless you fix problem 1) from above.

the way you are creating the object is wrong , should use as :
Base test;

Related

How does cin read strings into an object of string class?

Reading some documentation online I found that istream class was part of C++ long before the string class was added. So the istream design recognizes basic C++ types such as double and int, but it is ignorant of the string type. Therefore, there are istream class methods for processing double and int and other basic types, but there are no istream class methods for processing string objects.
My question is if there are no istream class methods for processing string objects, why this program works and how ?
#include <iostream>
int main(void)
{
std::string str;
std::cin >> str;
std::cout << str << std::endl;
return 0;
}
This is possible with the use operator overloading. As shown in the below example, you can create your own class and overload operator>> and operator<<.
#include <iostream>
class Number
{
//overload operator<< so that we can use std::cout<<
friend std::ostream& operator<<(std::ostream &os, const Number& num);
//overload operator>> so that we can use std::cin>>
friend std::istream &operator>>(std::istream &is, Number &obj);
int m_value = 0;
public:
Number(int value = 0);
};
Number::Number(int value): m_value(value)
{
}
std::ostream& operator<<(std::ostream &os, const Number& num)
{
os << num.m_value;
return os;
}
std::istream &operator>>(std::istream &is, Number &obj)
{
is >> obj.m_value;
if (is) // check that the inputs succeeded
{
;//do something
}
else
{
obj = Number(); // input failed: give the object the default state
}
return is;
}
int main()
{
Number a{ 10 };
std::cout << a << std::endl; //this will print 10
std::cin >> a; //this will take input from user
std::cout << a << std::endl; //this will print whatever number (m_value) the user entered above
return 0;
}
By overloading operator>> and operator<<, this allows us to write std::cin >> a and std::cout << a in the above program.
Similar to the Number class shown above, the std::string class also makes use of operator overloading. In particular, std::string overloads operator>> and operator<<, allowing us to write std::cin >> str and std::cout << str, as you did in your example.
Because std::string overload the >> and << operator to return the type std::istream and std::ostream
How they overload it, you can look in this link that Mat gives.
You can create your own class and overload operators, too. Here is an example:
class MyClass
{
int numberOne;
double numberTwo;
public:
friend std::ostream& operator<<(std::ostream &out, const MyClass& myClass);
friend std::istream& operator>> (std::istream& in, MyClass& myClass);
};
// Since operator<< is a friend of the MyClass class, we can access MyClass's members directly.
std::ostream& operator<<(std::ostream &out, const MyClass& myClass)
{
out << myClass.numberOne << ' ' << myClass.numberTwo;
return os;
}
// Since operator>> is a friend of the MyClass class, we can access MyClass's members directly.
std::istream& operator>> (std::istream& in, MyClass& myClass)
{
in >> myClass.numberOne;
in >> myClass.numberTwo;
return in;
}
int main()
{
MyClass myClass;
std::cin >> myClass;
std::cout << myClass;
}
Because of operator overloading.
In your case, including <iostream> will include <string>, a specialization of std::basic_string. And std::basic_string has the non-member functions operator<< and operator>> defined.
Similarly, you can also overload operator<< and operator>> for your own custom types.

ambiguous error overloading operator<< QdataStream subclass and personal class

I am working with Qt 5.10 and I have to subclass QDatastream and I overload the operator << with an other class, like this :
class myDataStream:public QDataStream
{
public :
myDataStream(QIODevice* device):QDataStream(device)
{}
};
class data
{
public:
data(double v):data_(v) {}
double getData() const {return data_;}
void record(myDataStream& stream) const;
private:
double data_;
};
void data::record(myDataStream &stream) const
{
stream<<getData();
}
myDataStream &operator<<(myDataStream &stream, const data &d )
{
stream<<d.getData(); //<------ Error here
return stream;
}
I have this error :
> error: use of overloaded operator '<<' is ambiguous (with operand types 'myDataStream' and 'double')
When I remove the const operator behind data like this :
myDataStream &operator<<(myDataStream &stream, data &d )
{
stream<<d.getData();
return stream;
}
I don't have error. The operator<< doesn't change the class data ... doesn' it ? the getData() method is const.
I don't understand.
Someone to help me ?
Finaly, I will follow the KubaOber advices (in comments of my questions) and make QDataStream a composition of my class instead of subclassing QDataStream.
Thanks to KubaOber for its advices !

making a class readable with >> and writable with << operators

I have an assignment question for my object orientated programming course that asks for the creation of a class.
I am a little stuck on this part of the questions
The class must, however, be readable using the >> operator and writable using the << operator. Do not use a friend function to overload the operators. Instead create suitable read and write methods and then overload the operators using a non-friend function.
class MyClass
{
public:
void ReadFrom(std::istream &is)
{
// read values from 'is' as needed...
}
void WriteTo(std::ostream &os) const
{
// write values to 'os' as needed...
}
};
std::istream& operator>>(std::istream &is, MyClass &cls)
{
cls.ReadFrom(is);
return st;
}
std::ostream& operator<<(std::ostream &os, const MyClass &cls)
{
cls.WriteTo(os);
return os;
}

cin and cout redeclaration

I have doubt in my mind regarding declaration of cin and cout object . As per my understanding cin and cout both object are accessible in main then they shouldn't have protected.in below code snippet i have overloaded both input and output operator and
while giving new name (ofstream obj) to user defined version of this operator , I am getting error like obj is protected and can't be accessed here. Anybody can suggest .
#include<iostream>
using namespace std;
class overload
{
public:
int var_a;
overload (int fun_a=10): var_a(fun_a) {}
friend ostream operator >> (ostream &output, overload &);
friend istream operator << (istream &input, overload &);
};
ostream &operator <<( ostream &output, overload &s1)
{
output<<"value of object output:"<<s1.var_a<<endl;
return output;
}
istream &operator >>( istream &input, overload &s1)
{
input >> s1.var_a;
return input;
}
int main()
{
overload s1,s2;
//ostream obj;
//obj<<"enter the value of object"
cout<<"enter the value of object";
cin>>s2;
cout<<s2;
return 1;
}
The relevant part is the & in ostream &. That makes it a reference.
In your main(), you can in fact do the same: ostream& obj = std::cout;. Just like the ostream& output in operator<< is valid while that function runs, ostream& obj will be valid while the main function runs.
[edit]
As for your comment, that's missing a critical point. std::cout is an std::ostream, yes. But std::ofstream (file) also is an std::ostream. Wait, you may say, one type is another type? Yes, in OO languages. Inheritance means that each object has the type used to construct it, but also any base types inherited from.
That's why you can pass a file stream to your operator<< overload. The std::ostream& can be initialized with any derived object.

Overloading C++ Insertion Operator (<<) for a class

I'm trying to write a class that overloads the insertion operator but in my header file I get the error.
Overloaded 'operator<<' must be a binary operator (has 3 parameters)
Here is my code:
.h file
ostream & operator<<(ostream & os, Domino dom);
.cpp file
ostream & operator<< (ostream & os, Domino dom) {
return os << dom.toString();
}
I'm following a text book and this is what they use as an example but its not working for me.. Any suggestions?
You probably put your operator<< inside a class declaration. That means it takes an extra hidden parameter (the this parameter). You need to put it outside of any class declaration.
The insertion operator (<<) can be used as a member function or a friend function.
operator << used as a member function
ostream& operator<<(ostream& os);
This function should be invoked as :
dom << cout;
In general if you are using the operator as a member function, the left hand side of the operator should be an object. Then this object is implicitly passed as an argument to the member function. But the invocation confuses the user and it does not look nice.
operator << used as a friend function
friend ostream& operator<<(ostream& os, const Domino& obj);
This function should be invoked as :
cout << dom;
In this case the object dom is explicitly passed as a reference. This invocation is more traditional and user can easily understand the meaning of the code.
/*insertion and extraction overloading*/
#include<iostream>
using namespace std;
class complex
{
int real,imag;
public:
complex()
{
real=0;imag=0;
}
complex(int real,int imag)
{
this->real=real;
this->imag=imag;
}
void setreal(int real)
{
this->real=real;
}
int getreal()
{
return real;
}
void setimag(int imag)
{
this->imag=imag;
}
int getimag()
{
return imag;
}
void display()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
};//end of complex class
istream & operator >>(istream & in,complex &c)
{
int temp;
in>>temp;
c.setreal(temp);
in>>temp;
c.setimag(temp);
return in;
}
ostream &operator <<(ostream &out,complex &c)
{
out<<c.getreal()<<c.getimag()<<endl;
return out;
}
int main()
{
complex c1;
cin>>c1;
// c1.display();
cout<<c1;
//c1.display();
return 0;
}