-3

I am trying to learn c++ and am creating a Vector2 class. I have this ToString() function in my Vector2 class which would allow me to print a Vector2 to the screen.

I also have this static const Vector2 variable called up, and I also want to print them using this ToString() function But it's giving an error. This is the Vector2::up implementation in .h and .cpp

When I store the Vector2::up in a Vector2 vec and print it like vec.ToString(), it works. But When i try to print Vector::up.ToString() it doesn't work.

This is what is in my Vector2 class, the Vector2::up and the ToString() Function.

"Vector2.h"

static const Vector2 up;

std::string ToString (int = 2);


"Vector2.cpp"

const Vector2 Vector2::up = Vector2 (0.f, 1.f);

std::string Vector2::ToString (int places)
{
    // Format: (X, Y)
    if (places < 0)
        return "Error - ToString - places can't be < 0";
    if (places > 6)
        places = 6;

    std::stringstream strX; 
    strX << std::fixed << std::setprecision (places) << this->x;
    std::stringstream strY;
    strY << std::fixed << std::setprecision (places) << this->y;

    std::string vecString = std::string ("(") +
                            strX.str() +
                            std::string (", ") +
                            strY.str() +
                            std::string (")");

    return vecString;
}

What i would like to do in my Main Function

"Main.cpp"

int main ()
{
    Vector2 vec = Vector2::up;
    cout << vec.ToString () << endl;
    cout << Vector2::up.ToString () << endl;

    cout << endl;
    system ("pause");
    return 0;
}

And I would like them to both print (0.00, 1.00) but the Vector2::up.ToString() is giving an error

1>c:\users\jhehey\desktop\c++\c++\main.cpp(12): error C2662: 'std::string JaspeUtilities::Vector2::ToString(int)': cannot convert 'this' pointer from 'const JaspeUtilities::Vector2' to 'JaspeUtilities::Vector2 &'

1 Answers1

1

As Vector::up is declared const, you may only access member functions that are declared const. While Vector2::ToString doesn't actually modify the vector, you haven't declared it const. To do this, declare it like this: std::string ToString (int places) const;

Knoep
  • 858
  • 6
  • 13