C++ 自动加载对象属性的默认构造函数

标签 c++ sfml

我是 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/

相关文章:

c++ - 6 "error LNK2019: unresolved external symbol"

c++ - 执行时间如何取决于使用 OpenMP 库的线程数量的增加?

c++ - SSE2编译器错误

c++ - 打印: Displaying an SHA1 hash in hexadecimal

c++ - 为什么打开 code::blocks exe 文件时出现错误?

c++ - 如何正确使用指针 vector ?

c++ - 尝试在 SFML 中使用 Sprite 和纹理进行继承

c++ - 球从特定角度穿过 Racket

c++ - c++标准库中的所有函数都需要有外部链接吗?

c++ - C++ 中的嵌套 For 循环三角形