Question

So I'm doing a program for vectors/matrixes processing and I can't overload index operator which I have to use (as a public method) to access private data of class. Code:

Header:

#ifndef WEKTOR_HH
#define WEKTOR_HH

#include "rozmiar.h"
class Wektor {
  float skladowa[ROZMIAR];

  public:
  float operator[] (int i);

};


std::istream& operator >> (std::istream &Strm, Wektor &Wek);
std::ostream& operator << (std::ostream &Strm, const Wektor &Wek);

#endif

Wektor.cpp:

#include "Wektor.hh"
#include <iostream>

float Wektor::operator[] (int i){
if(i<=ROZMIAR) return skladowa[i];
 else return skladowa[ROZMIAR];}


std::istream& operator >> (std::istream &Strm, Wektor &Wek){

  std::cin >> Wek[1] >> Wek[2] >> Wek[3];
  return Strm;}

std::ostream& operator << (std::ostream &Strm, const Wektor &Wek){

  std::cout << Wek[1] << Wek[2] << Wek[3] << std::endl;
  return Strm;}

Main:

#include <iostream>
#include "Wektor.hh"
#include "Macierz.hh"
#include "UkladRownanLiniowych.hh"



using namespace std;

int main()
{
  Wektor w1;
  cin >> w1;
  cout << endl << " Wczytano: " << endl << endl;
  cout << w1 << endl;
}

And I get ton of errors. For example, and also the one that bothers me is:

tobi@don-VM:~/PO/uklad$ make
g++ -c -g -Iinc -Wall -pedantic -o obj/main.o src/main.cpp
g++ -c -g -Iinc -Wall -pedantic -o obj/Wektor.o src/Wektor.cpp
src/Wektor.cpp: In function ‘std::istream& operator>>(std::istream&, Wektor&)’:
src/Wektor.cpp:11:12: error: no match for ‘operator>>’ (operand types are ‘std::istream {aka std::basic_istream<char>}’ and ‘float’)
   std::cin >> Wek[1] >> Wek[2] >> Wek[3];
            ^
src/Wektor.cpp:11:12: note: candidates are:
In file included from /usr/include/c++/4.8/iostream:40:0,
                 from inc/Wektor.hh:5,
                 from src/Wektor.cpp:1:

Why does it say that something is wrong with >> with float as second operator? I guess [] itself is working somehow, becase it interpretes it as a float type but why it cannot interact with >> ? I'm new to this so if it is something simple and obvious sorry but I can't find it. I'm aware it might be happening due to getting/not getting references but I can't figure it out.

Was it helpful?

Solution

The problem is that your operator returns by value:

float operator[] (int i);

When you pass the result of this directly to operator>>, you are passing a temporary, and this operator needs an lvalue reference, something it is allowed to modify. Technically speaking, you cannot bind an rvalue reference (the temporary) to a non-const reference in standard C++.

So, change the operator to return a reference:

float& operator[] (int i);

It is common practice to provide a const overload, returning a const reference:

const float& operator[] (int i) const;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top