Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple dot operator (c++ class)

I have to implement a class Vector, which sets coordinates of a multi-dimensional vector and will work when called with this specific code (I can't change this part):

  const int NumOfDimensions = 5;
  Vector x (NumOfDimensions);
  x.Set(0, 1.1).Set(1, 1.2).Set(2, 1.3).Set(3, 1.4).Set(4, 1.5); 
  x.print();

and the output has to be like this:

(1.1, 1.2, 1.3, 1.4, 1.5)

This is what I tried but couldn't get it to work:

class Vector {
float *coordinates;
int dimensions;

public:
Vector(int k)
{
coordinates = new float[k];
dimensions = k;
}
void Set(int k, float wsp)
{
    //Vector x(k+1);
    coordinates[k] = wsp;
    //return x;
}
void print()
{
    int i;
    cout<<"(";
    for(i=0; i<dimensions; i++)
    cout<<coordinates[i]<<", ";
    cout<<")"<<endl;
}
};

So I know function Set needs to be changed and probably return an object but I have tried lots of different ways and it just doesn't work. How should I modify it?

like image 583
mushisgosu Avatar asked Nov 25 '16 23:11

mushisgosu


1 Answers

If you want to be able to chain methods of that sort you need to return a reference:

Vector& Set(int k, float wsp) {
  // ...

  return *this;
}

I'd argue that even though you see a lot of that in other languages like Python, Ruby and so on, that interface isn't very C++.

You'd be better off using std::vector to store your coordinates, the C-style arrays are nothing but trouble. This code actually has a severe memory leak since you don't de-allocate with delete[], there's no destructor defined. Using a Standard Library container offloads that responsibility.

Another thing you can do to make this more natively C++ is to define a formatter for it so you can simply dump this to cout directly instead of having a clunky method called print which does it for you:

std::ostream& operator<<(std::ostream& stream, const Vector& vec);

That will permit the use of that formatter on any stream, not just cout.

like image 130
tadman Avatar answered Oct 21 '22 12:10

tadman