【问题标题】:Error when using std::vector and class objects使用 std::vector 和类对象时出错
【发布时间】:2014-06-05 00:37:35
【问题描述】:

这是错误“没有重载函数的实例...”。当我尝试传递多个论点时,我明白了。当我从文件中删除除一个之外的所有文件时,它工作正常。

这是我得到错误的 ObjectHandler.cpp。

    #include <SFML\Graphics.hpp>

    #include <memory>

    #include "ObjectHandler.hpp"
    #include "Platform.hpp"
    #include "Game.hpp"

    ObjectHandler::ObjectHandler()
    {
    platforms_.push_back(sf::Vector2f(0, 680), sf::Vector2f(40, 2000)
, sf::Color(100, 255, 40)); //This is the line where I get the error.
}

void ObjectHandler::render(sf::RenderWindow& window)
{
    for (auto platform : platforms_)
        platform.render(window);
}

这是课程的 hpp。

#ifndef PLATFORM_HPP
#define PLATFORM_HPP

#include <SFML\Graphics.hpp>

class Platform
{
public:
    Platform(sf::Vector2f position, sf::Vector2f size, sf::Color color);
    void render(sf::RenderWindow& window);

    sf::Vector2f getPosition() const;
    sf::FloatRect getBounds() const;
private:
    sf::RectangleShape platform_;
    sf::Vector2f position_;
};

#endif

这是cpp文件。

#include <SFML\Graphics.hpp>

#include "Platform.hpp"

Platform::Platform(sf::Vector2f position, sf::Vector2f size, sf::Color color)
    : position_(position)
{
    platform_.setPosition(position);
    platform_.setFillColor(color);
    platform_.setSize(size);
}

sf::FloatRect Platform::getBounds() const
{
    return platform_.getGlobalBounds();
}

sf::Vector2f Platform::getPosition() const
{
    return position_;
}

void Platform::render(sf::RenderWindow& window)
{
    window.draw(platform_);
}

我不明白为什么会发生这种情况......我试图通过搜索谷歌来获得答案,但没有运气。我真的很感激任何帮助! :)

【问题讨论】:

    标签: c++ class vector game-engine sfml


    【解决方案1】:

    您需要构建一个实际的平台,目前您只是试图将一堆Vector2fColor 对象推入您的platforms_ 向量中。

    例如

    platforms_.push_back(Platform(sf::Vector2f(0, 680),
        sf::Vector2f(40, 2000), sf::Color(100, 255, 40)));
    

    以下内容也应该起作用,编译器将从初始化列表中推断出类型,并最终调用与上例相同的构造函数。

    platforms_.push_back({sf::Vector2f(0, 680),
        sf::Vector2f(40, 2000), sf::Color(100, 255, 40)});
    

    但是,为了避免此处不必要的复制,您应该将其放置在向量上而不是推送它。

    platforms_.emplace_back(sf::Vector2f(0, 680),
        sf::Vector2f(40, 2000) , sf::Color(100, 255, 40));
    

    它的作用是在向量上就地构造对象,有关 emplace_back 的更多信息,请参阅cppreference

    【讨论】:

    • 我会调查的。 :)
    【解决方案2】:

    我觉得是

    platforms_.push_back(Platform(sf::Vector2f(0, 680), sf::Vector2f(40, 2000) , sf::Color(100, 255, 40)));
    

    而不是

    platforms_.push_back(sf::Vector2f(0, 680), sf::Vector2f(40, 2000) , sf::Color(100, 255, 40));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-24
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2022-09-21
      • 2014-08-20
      • 1970-01-01
      • 2011-05-06
      相关资源
      最近更新 更多