【问题标题】:C++ printing a static const classC++ 打印一个静态常量类
【发布时间】:2017-10-07 12:22:10
【问题描述】:

我正在尝试学习 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:\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 &'

【问题讨论】:

  • 发布minimal reproducible example。不要发布代码图片。
  • 复制粘贴代码和错误信息!
  • 我已经对其进行了编辑并发布了我的 ToString() 的代码
  • 请查看此C++ books 列表。

标签: c++ string class static constants


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 2010-10-07
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多