使用std :: vector和类对象时出错

时间:2014-04-21 00:18:46

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

这是错误"没有重载功能的实例......"。当我尝试传递多个参数时,我得到它。当我从文件中删除除了一个以外的所有文件时,它工作正常。

这是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_);
}

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

2 个答案:

答案 0 :(得分:1)

我认为是

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));

答案 1 :(得分: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

相关问题