C++打印静态const类
问题描述:
我想学习C++并创建Vector2类。我在Vector2类中有这个ToString()函数,它允许我将Vector2打印到屏幕上。C++打印静态const类
我也有这个静态常量Vector2变量调用了,我也想用这个ToString()函数打印它们但是它给出了一个错误。 这是在.h和Vector.Ppp
Vector2 :: up实现当我将Vector2 :: up存储在Vector2 vec中并将其打印为vec.ToString()时,它可以工作。 但是,当我尝试打印矢量:: 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 &'
答
由于Vector::up
声明const
,你可能只访问声明const
成员函数。虽然Vector2::ToString
实际上并未修改矢量,但您尚未声明const
。为此,请声明如下:std::string ToString (int places) const;
+0
非常感谢你,它的工作。 –
发布[MCVE]。不要张贴代码图片。 –
复制粘贴代码和错误信息! – 2017-10-07 12:31:26
我编辑了它并发布了我的ToString()的代码 –