c++是如何将事物保持在范围内的?
How does c++ keep things in scope?
更具体地说,我有一个看起来像这样的类:
class Ball {
public:
unsigned collider_size;
scionofbytes::MovementComponent movement;
scionofbytes::GraphicComponent graphic;
Ball(u_int init_collider_size, std::string texture_path) {
collider_size = init_collider_size;
movement = scionofbytes::MovementComponent();
graphic = scionofbytes::GraphicComponent(
(u_int) collider_size/2,
(u_int) collider_size/2,
texture_path
);
}
};
我接受texture_path并将其传递给图形组件,看起来像这样:
class GraphicComponent {
unsigned height;
unsigned width;
public:
sf::Texture texture;
sf::Sprite sprite;
GraphicComponent() {}
GraphicComponent(unsigned init_height, unsigned init_width, std::string texture_path) {
width = init_width;
height = init_height;
texture.loadFromFile(texture_path);
sprite.setTexture(texture);
}
};
当我通过传递texture_path实例化一个球对象时,我正在创建一个纹理作为图形组件的成员,然后将该纹理分配给图形组件的sprite成员。
当使用这个精灵成员绘制到屏幕上时,我面临着SFML已知的白框问题。
现在从我的理解来看,球对象保持活跃,图形组件成员也保持活跃,图形组件的纹理成员也是如此。
所以我的问题是,为什么这不起作用?当使用精灵在屏幕上作画时,我仍然会看到一个白色的盒子。为什么纹理会被破坏?
在您的Ball
类构造函数中,您正在制作GraphicComponent
的副本。IIRC sf::Sprite
仅保存对sf::Texture
的引用,因此您的副本可能最终以sf::Sptite
指向从其复制的对象中删除的sf::Texture
告终。
试着构造你的Ball
,而不复制你的GraphicComponent
:
class Ball {
public:
unsigned collider_size;
scionofbytes::MovementComponent movement;
scionofbytes::GraphicComponent graphic;
// Use initializer-list
Ball(u_int init_collider_size, std::string texture_path)
: collider_size(init_collider_size)
, movement()
, graphic((u_int) collider_size/2, (u_int) collider_size/2, texture_path)
{
// don't assign stuff here if you can avoid it
}
};
除了,你可能还想为你的GraphicComponent
类创建一个复制构造函数,以防止其他地方的损坏:
class GraphicComponent
{
unsigned height;
unsigned width;
public:
sf::Texture texture;
sf::Sprite sprite;
GraphicComponent()
{
}
GraphicComponent(unsigned init_height, unsigned init_width,
std::string texture_path)
{
width = init_width;
height = init_height;
texture.loadFromFile(texture_path);
sprite.setTexture(texture);
}
// Give it a copy constructor
GraphicComponent(GraphicComponent const& other)
: height(other.height)
, width(other.width)
, texture(other.texture)
, sprite(texture) // make it point to the new Texture not the other one
{
}
};
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 错误:未在此范围内声明'reverse'
- 并行用于C++17中数组索引范围内的循环
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 不计算一个范围内的完美数
- 错误:"imread"未在此范围内声明
- 我在范围内未声明的错误类有问题
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- 我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?
- 未在此范围内声明错误 'xy'
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 命名空间范围内的外部 - GCC vs clang vs msvc
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 如何仅使用 While 循环在给定范围内找到可被 7 整除的计数整数
- Socklen_t未在此范围内声明
- 错误:'[' 之前预期的非限定 id 和错误:'users'未在此范围内声明
- 查找给定范围内最长连续 1 的频率
- "Main"已在当前范围内声明
- c++ 变量在宏的扩展中没有在这个范围内声明
- 变量不在 lambda 的范围内