[英]C++ printing a static const class
I am trying to learn c++ and am creating a Vector2 class.我正在尝试学习 C++ 并正在创建一个 Vector2 类。 I have this ToString() function in my Vector2 class which would allow me to print a Vector2 to the screen.我的 Vector2 类中有这个 ToString() 函数,它允许我将 Vector2 打印到屏幕上。
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.我也调用了这个静态 const Vector2 变量,我也想使用这个 ToString() 函数打印它们但是它给出了一个错误。 This is the Vector2::up implementation in .h and .cpp这是 .h 和 .cpp 中的 Vector2::up 实现
When I store the Vector2::up in a Vector2 vec and print it like vec.ToString(), it works.当我将 Vector2::up 存储在 Vector2 vec 中并像 vec.ToString() 一样打印它时,它可以工作。 But When i try to print Vector::up.ToString() it doesn't work.但是当我尝试打印 Vector::up.ToString() 时它不起作用。
This is what is in my Vector2 class, the Vector2::up and the ToString() Function.这就是我的 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;
}
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我希望他们都打印 (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 &'
As Vector::up
is declared const
, you may only access member functions that are declared const
.由于Vector::up
声明为const
,您只能访问声明为const
成员函数。 While Vector2::ToString
doesn't actually modify the vector, you haven't declared it const
.虽然Vector2::ToString
实际上并未修改向量,但您尚未将其声明为const
。 To do this, declare it like this: std::string ToString (int places) const;
为此,请像这样声明它: std::string ToString (int places) const;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.