C++打印静态常量类
C++ printing a static const class
我正在尝试学习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;
相关文章:
- 常量静态成员函数
- 常量静态成员函数:有另一种方法可用吗?
- C++常量静态字符* 数组
- 为什么常量静态变量应该在结构中初始化?
- 使用 constexpr 初始化非常量静态字符串
- 初始化常量静态 std::map unique_ptr作为值
- 静态函数常量静态成员函数
- 不能将值 120 分配给静态常量无符号字符或将值 200 分配给常量静态无符号 int
- 静态常量与常量静态
- 声明"静态常量"和"常量静态"有什么区别
- 常量静态成员初始化 - 类定义内部与外部类定义
- 为什么一个非常量静态成员会有多个定义
- 在类内部使用常量-静态与非静态
- 模板/泛型类中的非常量静态成员- c++与c#
- 类中的常量静态函数指针~如何初始化它
- 无法访问常量静态标准::映射枚举结构
- C++初始化非常量静态成员变量
- When是一个非静态常量数据成员,比常量静态成员更有用
- C++11 MinGW 4.9.1 shared_ptr和常量静态类字段结果"Undefined reference"
- c++动态初始化常量静态向量