我是 C++ 编程新手,我遇到的问题是 WorldMapState
类自动创建属性 tile_map (TileMap)
的新对象。如果 TileMap 的构造函数没有参数,则没有问题,但我添加了三个参数,并且 WorldMapState 会自动尝试使用空构造函数创建对象。为什么 C++ 以这种方式工作?我该如何解决这个问题?
#pragma once
#include <SFML\Graphics.hpp>
namespace SaGa {
class TileMap : public sf::Drawable, public sf::Transformable
{
public:
TileMap(unsigned int width, unsigned int height, unsigned int tileSize);
bool load(const std::string& tileset, sf::Vector2u tileSize, const int* tiles);
void setSprite(unsigned int value, unsigned int x, unsigned int y);
private:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
sf::VertexArray m_vertices;
sf::Texture m_tileset;
unsigned int _width;
unsigned int _height;
unsigned int _tileSize;
};
}
主类
#pragma once
#include <SFML\Graphics.hpp>
#include "State.hpp"
#include "Game.hpp"
#include "TileMap.hpp"
#include <vector>
namespace SaGa
{
class WorldMapState : public State
{
public:
WorldMapState(GameDataRef data);
void Init();
void HandleInput();
void Update(float dt);
void Draw(float dt);
private:
GameDataRef _data;
//sf::Texture _tilemap;
//std::vector<sf::Sprite> _tiles;
TileMap _tilemap;
};
}
最佳答案
If TileMap has no arguments on constructor there is no problem, but I added three arguments and WorldMapState automatically tries to create an object with empty constructor. Why C++ works in that way?
因为您的 TileMap
构造函数需要 3 个参数。它们不是可选的。向 TileMap
添加另一个不带参数的构造函数:
public:
TileMap();
TileMap(unsigned int width, unsigned int height, unsigned int tileSize);
或者使用现有构造函数的默认值:
public:
TileMap(unsigned int width = 0, unsigned int height = 0, unsigned int tileSize = 0);
或者通过内联初始化使用 3 个参数正确初始化 _tilemap
:
private:
// ...
TileMap _tilemap{0, 0, 0};
或者在 cpp 文件的构造函数定义中使用构造函数初始值设定项列表:
WorldMapState::WorldMapState(GameDataRef data)
: _tilemap(0, 0, 0)
{
// ...
}
当然,传递适合您情况的值。
关于C++ 自动加载对象属性的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56102459/