没有用于初始化类的匹配构造函数

No matching constructor for initialisation of class

本文关键字:构造函数 用于 初始化      更新时间:2023-10-16

看不出我做错了什么...

我的游戏窗口.h有代码 -

#include <iostream>
#include <string>
using namespace::std;
class GameWindow{
    string WindowType;
    string WindowName;
    int TopLeftX,TopLeftY;
    int Height,Width;
    bool GetBoxed;
public:
    GameWindow(string WinType, string WinName,int TLX,int TLY,int y,int x,bool box);
    void SetHeight(int y);
    void SetWidth(int x);
    void SetTopLeftY(int TLY);
    void SetTopLeftX(int TLY);
};

源文件代码是——

#include "GameWindow.h"
GameWindow::GameWindow(string WinType, string WinName,int TLX,int TLY,int y,int x,bool box){
    WindowType = WinType; WindowName = WinName;
    TopLeftX = TLX; TopLeftY = TLY;
    Height = y; Width = x;
    GetBoxed = box;
};
void GameWindow::SetHeight(int y){Height = y;}
void GameWindow::SetWidth(int x){Width = x;}
void GameWindow::SetTopLeftY(int TLY){TopLeftY=TLY;}
void GameWindow::SetTopLeftX(int TLX){TopLeftX=TLX;}

所以在另一个源文件中,我尝试创建一个 GameSpace 的向量,并在每次向向量添加一个时调用构造函数 -

int OffsetX =5;
    vector<GameWindow>GameSpace;
    GameSpace.resize(8);
    GameSpace[0] = GameWindow("MonstersLeftWin", "Misc", 
    (getmaxx(stdscr)-22-OffsetX), 2, 1, 22, true);

我收到"没有匹配的游戏窗口初始化构造函数"错误。根本看不出我做错了什么!

如果我有 - 我也会收到错误 -

    GameSpace[0] = *new GameWindow("MonstersLeftWin", "Misc", 
    (getmaxx(stdscr)-22-OffsetX), 2, 1, 22, true);

仍然不确定我是否需要那里的"新"。

感谢您的帮助。

这里的问题是GameSpace.resize(8)语句。一旦您提供了自定义构造函数,编译器将不再为您生成默认构造函数。但是,std::vector将在调整大小调用中默认初始化元素。

提供默认构造函数(首选):GameWindow()

或者使用void resize (size_type n, const value_type& val);重载

在此语句中

GameSpace.resize(8);

编译器尝试调用类游戏窗口的默认构造函数。但是,该类没有默认构造函数。因此,编译器会发出错误。

而不是

GameSpace.resize(8);

例如,您可以编写以下内容

GameSpace.resize( 8, { "", "", 0, 0, 0, 0, false }  );