I want to overload the >> operator in c++ so that my class of vectors can take input in the form [1 2 3 4 5].
For example:
class A
{
public:
A() {}
A(const std::vector<int>& source)
: v_(source)
{
}
// returns an immutable reference to v_
const std::vector<int>& get_v() const
{
return v_;
}
// returns a mutable reference to v_
std::vector<int>& get_v()
{
return v_;
}
private:
std::vector<int> v_;
};
int main (){
A my_vector;
while (cin >> my_vector)
// do some other computations
}
Right now I’ve declared the overloading function for >> like this:
istream& operator>> (istream & stream, A vector){
}
But I’m confused on what I need to do next to store what ever is in my cin to my A object. I assume I need to check for both [] in the input to make sure it is accepted otherwise exit the application. Any suggestions
The first thing that you need is to pass the second argument by reference, so that the object modified inside the operator is the same object that you are reading into.
The next thing that you need is to actually read from input into your internal vector. For that You need to skip the first
[, and then read the numbers until you find the].The first character can be read into a char, then you can use
copyto fill in the vector, and finally another read into a char to read the]:Now, this is a sketch, and you will need to handle errors, in particular what happens if the first character is not
[or the last character is not]…Side notes:
It is usually not a good idea to provide full access to your internal data, as you are doing with the
get_v()method. That is, there is no point in makingv_private if you are just going to provide full access… if it needs to be accessible make it public and you can avoid having to write the two accessor functions.