C++;打印静态常量类 我正在学习C++,并且正在创建一个向量类。我的Vector2类中有一个ToString()函数,它允许我将Vector2打印到屏幕上

C++;打印静态常量类 我正在学习C++,并且正在创建一个向量类。我的Vector2类中有一个ToString()函数,它允许我将Vector2打印到屏幕上,c++,string,class,static,constants,C++,String,Class,Static,Constants,我还调用了这个static const Vector2变量,我还想使用这个ToString()函数打印它们,但它给出了一个错误。 这是.h和.cpp中的Vector2::up实现 当我将Vector2::up存储在Vector2 vec中并像vec.ToString()一样打印它时,它就工作了。 但当我尝试打印Vector::up.ToString()时,它不起作用 这就是我的Vector2类中的内容,Vector2::up和ToString()函数 "Vector2.h" static co

我还调用了这个static const Vector2变量,我还想使用这个ToString()函数打印它们,但它给出了一个错误。 这是.h和.cpp中的Vector2::up实现

当我将Vector2::up存储在Vector2 vec中并像vec.ToString()一样打印它时,它就工作了。 但当我尝试打印Vector::up.ToString()时,它不起作用

这就是我的Vector2类中的内容,Vector2::up和ToString()函数

"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;
}

由于声明了
Vector::up
,您只能访问声明了
const
的成员函数。虽然
Vector2::ToString
实际上并没有修改向量,但您尚未声明它
const
。为此,如下声明:
std::string-ToString(int-places)const

发布一条消息。不要张贴代码图片。复制并粘贴代码和错误消息!我已经编辑并发布了我的ToString()的代码。请看一下这个列表。
"Main.cpp"

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

    cout << endl;
    system ("pause");
    return 0;
}
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 &'