C++打印静态常量类

C++ printing a static const class

本文关键字:常量 静态 打印 C++      更新时间:2023-10-16

我正在尝试学习c ++并正在创建一个Vector2类。我的 Vector2 类中有这个 ToString() 函数,它允许我将 Vector2 打印到屏幕上。

我也调用了这个静态 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;
}

我想在我的主函数中做什么

"Main.cpp"
int main ()
{
    Vector2 vec = Vector2::up;
    cout << vec.ToString () << endl;
    cout << Vector2::up.ToString () << endl;
    cout << endl;
    system ("pause");
    return 0;
}

我希望他们都打印(0.00,1.00),但Vector2::up。ToString() 给出错误

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

由于Vector::up被声明为const,因此您只能访问声明为const的成员函数。虽然Vector2::ToString实际上并没有修改向量,但您尚未将其声明为const 。为此,请像这样声明:std::string ToString (int places) const;