I've been trying to overload the >> operator. I have a class that has two private variables:
Class Complex
{
private:
double real;
double imaginary;
};
In addition I have a friend function that overloads the >> operator:
friend istream & operator>>(istream &is, Complex &c)
In the implementation of the function I've tried many ways to write into the variable of object c but I keep getting an error no operator >> matches these operands
I looked around and read that I need to write into a reference of the variable, so I tried the following:
istream & operator>>(istream &is, Complex &c)
{
using std::cout;
double &r = c.real;
cout << "real: " << is >> r;
return is;
}
However this still gives me the same error.
I'm slightly confused as I tried is >> c.real and didn't work.
On one of the answers in a similar SO question, someone suggested writing into a local variable and setting the object variable it, something like:
double d;
cin >> d;
setReal(d);
I'm trying to find a more simpler way to achieve this rather than using a method or setting the variable to a local one.
The solution could be a simple one, but I'm really just a beginner in C++, so please take it easy on me :P.
Test case:
using std::cin;
Complex c;
cin >> c;
Exact error message:
Error 1 error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::basic_ostream<_Elem,_Traits>' (or there is no acceptable conversion)
The error is on this line:
cout << "real: " << is >> r;
This is interpreted as
((cout << "real: ") << is) >> r
The problem here is that you can't have a line like this where you switch from outputting to cout and start reading from is. A better way to do this would be
cout << "real: ";
is >> r;
That said, this is a very bad idea. You should not have operator >> display a prompt, since it means that if you want to read in an object of your type from a file, every time you do so you will get the prompt "real" displayed on-screen. You should have operator >> just read the representation, and explicitly prompt before reading if that's what you want to do.
Hope this helps!
The error is on this line:
cout << "real: " << is >> r;
Did you mean to use << instead of >> on that last one? Since you used >>, it's trying to write "is" into cout, but there is no overload of operator<< that takes a basic_ostream and a basic_istream.
Related
This question already has answers here:
Can't Overload operator<< as member function
(3 answers)
Closed 8 months ago.
From c++ how to program 10th edition by deitel
//Fig. 10.3: PhoneNumber.h
//PhoneNumber class definition
#ifndef PHONENUMBER_H
#define PHONENUMBER_H
#include <iostream>
#include <string>
class PhoneNumber
{
friend std::ostream& operator<<(std::ostream&, const PhoneNumber&);
friend std::istream& operator>>(std::istream&, PhoneNumber&);
private:
std::string areaCode; //3-digit area code
std::string exchange; //3-digit exchange
std::string line; //4-digit line
};
#endif // PHONENUMBER_H
//Fig. 10.4: PhoneNumber.cpp
//Overloaded stream insertion and stream extraction operators
#include <iomanip>
#include "PhoneNumber.h"
using namespace std;
//overloaded stream insertion operator; cannot be a member function
//if we would like to invoke it with cout << somePhoneNumber;
ostream& operator<<(ostream& output, const PhoneNumber& number)
{
output << "Area code: " << number.areaCode << "\nExchange: "
<< number.exchange << "\nLine: " << number.line << "\n"
<< "(" << number.areaCode << ") " << number.exchange << "-"
<< number.line << "\n";
return output; //enables cout << a << b << c;
}
//overloaded stream extraction operator; cannot be a member function
//if we would like to invoke it with cin >> somePhoneNumber;
istream& operator>>(istream& input, PhoneNumber& number)
{
input.ignore(); //skip (
input >> setw(3) >> number.areaCode; //input area code
input.ignore(2); //skip ) and space
input >> setw(3) >> number.exchange; //input exchange
input.ignore(); //skip dash (-)
input >> setw(4) >> number.line; //input line
return input; //enables cin >> a >> b >> c
}
//Fig. 10.5: fig10_5.cpp
//Demonstrating Class PhoneNumber's overloaded stream insertion
//and stream extraction operators.
#include <iostream>
#include "PhoneNumber.h"
#include <string>
using namespace std;
int main()
{
PhoneNumber phone; //create object phone
cout << "Enter phone number in the form (555) 555-5555:" << endl;
//cin >> phone invokes operator>> by implicitly issuing
//the non-member function call operator>>(cin, phone)
cin >> phone;
//cout << phone invokes operator<< bby implicitly issuing
//the non-member function call operator<<(cout, phone)
cout << phone << endl;
}
I understand from the book that the overloaded operator function for binary operator can be member function only when the left operand is an object of the class in which the function is a member because the member function can only be accessed by left operand which is the object of the class.
however I don't understand this part
" The overloaded stream insertion operator (<<) is used in an expression in which the
left operand has type ostream&, as in cout << classObject. To use the operator in this
manner where the right operand is an object of a user-defined class, it must be overloaded
as a non-member function. To be a member function, operator << would have to be a
member of class ostream. This is not possible for user-defined classes, since we are not
allowed to modify C++ Standard Library classes. "
my question is
whether the stream extraction and insertion operator is part of the ostream and istream respectively?
what does the part highlighted in bold mean?
My guess is that we cannot add user defined function into the C++ Standard Library class but the part in bold makes me kind of confused. do we have to add the operator << as member of class ostream to make the overloaded operator function as member function of ostream?
I always thought that stream << and >> operator were part of ostream and istream respectively.
Correct me if I am wrong. thank you in advance.
No, not for regular user defined types. The functions you made into friends in your class definition are free functions:
std::ostream& operator<<(std::ostream&, const PhoneNumber&);
std::istream& operator>>(std::istream&, PhoneNumber&);
std::basic_ostream does have some operator<< member overloads for fundamental types, such as int, and some types defined in the standard library though. If you inherit from some of those standard types, like std::basic_streambuf<CharT, Traits>, you will be able to use the basic_ostream::operator<< member overloads for those types.
It means that you are not allowed to modify the definition of std::basic_ostream to add std::basic_ostream& operator<<(const PhoneNumber&) as a member function.
You might have already read about overloading. There is not one function called operator<<, there are multiple. Some of those are class members, others aren't. The compiler will choose the right operator<< based on the two arguments.
When the compiler looks for overloads of operator<<, it will check class methods of the object on the left-hand side only. (If that's even a class. In 1<<3==8 the arguments are ints). For that reason, when the compiler sees std::cout << YourClass{} it won't look for YourClass::operator<<(ostream&).
If you wrote YourClass{} << std::cout (VERY unusual), the compiler would look in YourClass. Rules are rules, and there is no hard rule that forbids that order. But it would break the usual chaining of std::cout << a << b << c, so it's very inconvenient. So to make the usual chaining work, we do it as your textbook tells you.
Im working with the book SFML Game Development by Examples and I dont really get what this sentence does. I've never seen something like this
void Anim_Directional::ReadIn(std::stringstream& l_stream){
l_stream >> m_frameStart >> m_frameEnd >> m_frameRow
>> m_frameTime >> m_frameActionStart >> m_frameActionEnd;
}
In C++ they got the "bright" idea of overloading the rightshift and leftshift operators with streams to represent serialization/deserialization.
stream >> var
means "read var from stream".
Symmetrically
stream << var
mean "put var into stream"
The operation of "streaming" in or out also returns the stream, so you can chain operations like:
stream >> var1 >> var2;
Note that the "streaming" was chosen just because of the look and because the priority was considered reasonable, but it's still just an overloaded operator and implies for example no strict sequence of evaluation. For example in:
stream << f() << g();
may be function g is called (somewhat surprisingly) before function f.
NOTE: the sequencing problem was handled by hammering this special case in last C++ standard (C++17). While it doesn't hold in general it's guaranteed for shift operators (presumably for this specific reason). So in f()+g() may be f is called later than g, but in f()<<g() this cannot happen.
C++ allows you to overload >> and << operators. std::stringstream is a derivative of std::istream and it inherits the >> operator overloads of std::istream.
The std::istream has a bunch of overloads for many common types. You can find a list of them here.
A typical std::istream >> operator overload looks as follows:
std::istream& operator>>(std::istream& stream, YourType& var) {
/*
** code here to parse and read a 'YourType' into 'var'
*/
/* var is set */
return stream; /* return the same stream to allow chaining */
}
When you do some_stream >> YourType_object, the matching >> operator overload is invoked. In the aforementioned case, our operator overload is invoked with stream parameter taking some_stream and var taking YourType_object.
The >> overloads (and << overloads too) intelligently return the stream which they operated; thereby, allowing a series of >> operators to be chained.
I assigned myself some homework over the summer, and the project I am 98% finished with has come to a standstill due to this one problem.
I have a class called Mixed. It contains member data for a whole number, a numerator, and a denominator. I need to overload all of the common operators to allow multiplication, addition, comparison and streaming of objects of type Mixed. I have all the operators overloaded except for >> (the extraction operator).
All mixed numbers read in will be of format:
whole numerator/denominator
ex: 1 2/3, 0 7/8, -3 18/5, 0 -1/89
Header: friend istream& operator>> (istream &, Mixed);
CPP file: istream& operator>> (istream &in, Mixed m) {...}
For the assignment, I am limited to the iostream and iomanip libraries. My plan was to read in the values from the stream and assign them to temporary int variables (w, n, d) which I would then use with the Mixed constructor to create object m. Unfortunately, I cannot think of a way to separate the numerator and denominator. They are both ints, but they have a char (/) between them.
I cannot use getline() with its delimiter, because it assigns data to a char array, which I do not believe I can convert to an int without another library.
I cannot use a char array and then segment it for the same reason.
I cannot use a while loop with get() and peek() because, again, I do not think I will be able to convert a char array into an int.
I cannot use a string or c-string and then segment it because that requires external libraries.
Once again, I need to split a value like "22/34" into 22 and 34, using only iostream and iomanip. Is there some fairly obvious method I am overlooking? Is there a way to implicitly convert using pointers?
You could first extract the nominator, then the separating character, and then the denominator.
Example for illustration:
istream& operator>> (istream &in, Mixed &m) {
int num, denom;
char separ;
in >> num;
in.get(separ);
if (separ != '/')
in.setstate(ios::failbit);
in >> denom;
if (in) {
// All extraction worked
m.numerator = num;
m.denominator = denom;
}
return in;
}
Once again, I need to split a value like "22/34" into 22 and 34, using
only iostream and iomanip.
Couldn't you just read in the first integer, use get to get the next character, and then read the second integer? Something like this:
#include <iostream>
int main() {
using std::cin;
using std::cout;
int num;
int den;
while(cin) {
cin >> num;
if (cin.get() != '/') {
// handle error
}
cin >> den;
cout << num << "/" << den << std::endl;
}
return 0;
}
You can then make sure that the character read between the two integers was a '/' and handle appropriately if it isn't.
I have the following block of code trying to overload the >> operator:
istream &operator >> (istream &stream, const Currency &obj){
cout << "Dollars: ";
stream>>obj.dollars;
cout<< "Cents: ";
stream>> obj.cents;
return stream;
}
But when I call cin>>newMoney from my main program it keeps repeating "DOLLARS:" over and over again in an endless loop like below:
Any ideas why?
I bet you have a Currency constructor that takes an 'int'. So stream>>obj.dollars; is the same as stream>>Currency(obj.dollars);. The function you pasted outputs "Dollars: " and then calls itself, outputting "Dollars: " again and then repeating forever.
I'd suggest making the constructor explicit so it doesn't misfire on you.
There is no enough information in your code (as of now). Till you post more code, all I can say is this, which is also important for you to note down: since you overload >> to take input, the object obj should be passed by non-const reference, so remove const from the second parameter, and make it look like this:
istream &operator >> (istream &stream, Currency &obj)
I don't quite understand what this means...I'm just learning C++ from my very very very basic Python experience...and so this may be a very stupid question. My question is...say you have your classic "Hello World" program and you have the line:
cout<<"Hello World!"<<endl;
what does the << mean...because I was just looking at using input in C and saw that you'd do something like:
int i;
cin>>i;
and I noticed that it has >> instead of << and I've read that those are bitwise shifts...and I don't exactly understand what those are...but I think it might be different here...Help...Thanks in advance
In Python, you can implement __lshift__ and __rshift__ to do whatever you want. In C++, it is the same - while the classic meaning is bitwise shift right and bitwise shift left, you can make it do whatever you want.
This is probably one of the most blatant violations of "sensible" operator overloading in C++, but that is just how std::ostream and std::istream work. For all of the C++ lovers out there (myself included), I apologize for this strange choice of operators. Just think of it as the direction that the data flows in (cout << foo puts a foo in cout, cin >> foo puts cin in foo), smile and be happy. From a newcomer, it really doesn't make sense, but drink the C++ Kool Aid and you'll be OH YEAH about it. Trust me.
Operators can have different meanings when applied to different types, and C++ allows the developer to overload operators to do just that. It's a powerful technique that should be used cautiously, since it's really easy to make programs unreadable if you overload unjudiciously.
Therefore >> and << are bit shift operators when the left side is an integer, but input and output operators when the left side is an I/O stream or similar. Read them as arrows pointing which direction the data flows.
Originally, it did mean bitshift. And you can still use it as a bitshift for an int (or other basic type).
Classes let you redefine operators. This allows you to create iterators, for which ++ actually does what you want (iterates to the next element), by modifying an internal member appropriately.
<< and >> are also operators, which can be redefined for classes, and this allows them to be used as "stream insertion/extraction operators".
The ostream class actually defines ostream& operator<< (Type); and the istream class defines istream& operator>> (Type&);
You can see more details about i/ostream here: http://www.cplusplus.com/reference/iostream/
Full details of ostream's operator<< and of istream's operator>>.
You can even write your own such operators to be able to do cout << myclass;:
class MyClass{ ... };
ostream& operator<< (ostream& os, const MyClass& myclass) {
// code to insert it, usually something like:
return os << myClass.a << ' ' << myClass.b;
}
// and now you can do this:
MyClass m;
std::cout << m;
The << and >> operators are bitshift operators, but, for input/output streams, they are overloaded (=>their meaning is redefined) so that they are used to insert/extract stuff into the streams.
I think they were used because they look intuitive (they indicate the direction of the stream of data) and because they are almost never used for other purposes.
Instead of saying
print "Hello" + "world" #I know, you wouldn't actually do it like this.
where "print" is the command and "hello world" is your text,
c++ works as
cout << "Hello" << "World"; // or like this. But...
int i = 42;
cout << "The answer is: " << i; //you may want to do this
c++ uses "cout" as the command and "<<" as a joiner, or, more technically, an operator used on the out stream.
cin works similarly where the >> is just an operator that works on the in stream.