使用std::vector和类对象时出错
Error when using std::vector and class objects
这是错误"没有重载函数的实例…"。当我试图传递多个参数时,会得到它。当我从文件中删除除一个以外的所有文件时,它工作得很好。
这是我得到错误的ObjectHandler.cpp。
#include <SFMLGraphics.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 <SFMLGraphics.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 <SFMLGraphics.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_);
}
我不明白为什么会发生这种事。。。我曾试图通过搜索谷歌来获得答案,但没有成功。我真的很感激任何帮助!:)
您需要构建一个实际的平台,此时您正试图将一堆Vector2f
和Color
对象推送到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));
这样做的目的是在向量上的适当位置构建对象,有关template_back的更多信息,请参阅cppreference。
我认为是
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));
相关文章:
- 在c++中访问int到类对象的映射时出错
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 按基类对象访问派生类资源时出错
- ./main:加载共享库时出错:libopencv_highgui.so.4.0:无法打开共享对象文件:没有这样的文件或
- 在 c++ 的构造函数中分配对象向量时出错
- 从主线程中询问运行对象表 (ROT) 时出错
- 加载共享库时出错:libbsoncxx.so._noabi:无法打开共享对象文件:没有此类文件或目录
- 从 Arduino 中的自定义C++库构造对象时出错
- 在 boost::heap::p riority_queue 中推送结构对象时出错
- 创建 OpenGL 对象期间出错
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 创建类对象时出错
- 尝试将对象用作类的属性时出错
- 擦除矢量中的对象时出错.如何将移动作业运算符添加到我的类中
- 编译创建 Eigen::ThreadPoolDevice 对象的代码时出错
- 尝试使用构造函数创建对象时出错
- 从模板类初始化对象时出错.参考类模板实例化
- 加载共享库时出错:无法在外部硬件上打开共享对象文件:
- 可变大小的对象可能无法初始化 尽管初始化了,但出错
- 删除时出错:表达式必须是指向完整对象类型的指针