【问题标题】:How to properly use pointers with functions and returning?如何正确使用带有函数和返回的指针?
【发布时间】:2018-08-26 14:38:38
【问题描述】:

我想在一个类中有一个 sf::Texture's(sfml) 数组,然后希望有一个函数返回指向该数组(向量)中特定项的指针。 然后我想将它传递给需要 sf::texture 的 sprite.SetTexture(也是 SFML)。 但我无法让它工作,这是我目前拥有的,我把不重要的东西遗漏了:

class SpriteTextures
{
public:
    std::vector<sf::Texture> Textures;

    //code to fill the vector here

    sf::Texture *GetSecondTexture()
    {
        return &Textures[1];
    }
};

class DrawSprite
{
    sf::Texture *texture;
    sf::Sprite sprite;

public:
    void SetSpriteTexture()
    {
        SpriteTextures SprTexs;
        texture = SprTexs.GetSecondTexture();
        sprite.setTexture(texture, true); // Gives error about no suitable constructor exists to convert from sf::Texture * to sf::Texture

        // do some other stuff with the texture here.
    }
};

这就是Sprite::setTexture的函数定义:

void setTexture(const Texture& texture, bool resetRect = false);

它给出的错误我已在代码中作为注释(在 setTexture 函数旁边) 所以我想要的是,不是将向量项复制到 DrawSprite 类中的纹理变量,而是希望 DrawSprite 中的 *texture 指向向量中的项。 但我确实想首先在 DrawSprite 中设置 *texture,因为我也想将它用于其他事情。 所以我希望能够用我的*纹理提供 setTexture 函数,并让它读取 SpriteTextures 类中向量中的 sf::Texture。(而不是在 DrawSprite 类本身的纹理变量中读取它的副本。

如果有人理解我刚才所说的话,有人可以帮我让它正常工作吗?

谢谢!

【问题讨论】:

  • 在尝试使其与复杂类一起使用之前,先尝试使其与int[] 一起使用。
  • 如果您不知道如何从指针中获取引用,那么也许您应该在进入第三方库(如 SFML)之前阅读 C++ 书籍。这是非常基本的信息。
  • 我无法让它工作,这就是我问的原因。
  • @TimLeijten:不,您显然不知道如何从指针中获取引用,否则您会意识到 Stephen 的评论正是这样做的。

标签: c++ function pointers vector sfml


【解决方案1】:

基本上,在这个函数中:

void SetSpriteTexture()
{
    SpriteTextures SprTexs;
    texture = SprTexs.GetSecondTexture();
    sprite.setTexture(texture, true); // Gives error about no suitable constructor exists to convert from sf::Texture * to sf::Texture

    // do some other stuff with the texture here.
}

您将sf::Texture* 传递给sprite.setTexture(..),而实际上,它需要sf::Texture&amp;。只需将调用更改为:

sprite.setTexture(*texture, true);

或者,让您的其他函数简单地返回一个引用:

sf::Texture& GetSecondTexture()
{
    return Textures[1];
}

这意味着您现在默认返回精灵所需的内容。当然,您必须确保您的纹理容器至少与您的精灵一样长,否则纹理引用将不再有效。

编辑

另外,看看 cmets,您似乎对 * 运算符和 &amp; 运算符有点困惑。这是一个快速的 sn-p 解释这些运算符的各种用例:

int a = 42;

int* b = &a; // * Declares pointer. & Takes address of a
int& c = a;  // & Declares reference.

*b = 32;     // * Dereferences the pointer, meaning you get the value it points to.
             // a, and c are now 32, and b points to a, which holds the value 32.

【讨论】:

  • 谢谢,没想到这么简单。会去图书馆找一本c++的书来学习一些指点。
  • 第二种选择不能解决问题。它只需要他获取返回值的地址,以便将其存储在texture 变量中。
  • @TimLeijten 还要检查更新的编辑以查看额外的语法解释。
  • @BenjaminLindley 第二种选择也需要重新设计该类,是的。存储引用或根本不存储它。由于这是一个最小的示例,我决定包含一个替代方案,因为我不知道完整程序的外观。
  • 谢谢,那怎么做更聪明呢?我的函数是否返回指针或引用?
猜你喜欢
  • 2018-03-01
  • 2012-11-28
  • 2015-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多