[英]c++ no matching constructor when constructor is declared
我正在嘗試在 c++ 中創建一個非常基本的文本游戲。 我的問題是我的 State class 代表當前游戲 state。
聲明 class 的 .h 文件:
#ifndef TEXTADV_STATE_H
#define TEXTADV_STATE_H
#include "Room.h"
#include "GameObject.h"
class State {
Room *currentRoom;
Room *previousRoom;
public:
explicit State(Room *startRoom);
static std::list<GameObject*> inventory;
void goTo(Room *target);
void goBack();
void announceLoc() const;
static void addObj(GameObject *obj);
static void remObj(Gameobject *obj);
Room* getCurrentRoom() const;
Room* getPrevRoom() const;
};
#endif //TEXTADV_STATE_H
對應的.cpp文件中構造函數的定義:
State::State(Room *startRoom) : currentRoom(startRoom) {};
在 main.cpp 中,我將 State object 初始化為:
State *currentState;
將值分配給 currentState 時出現此錯誤:沒有用於初始化“State”候選構造函數(隱式默認構造函數)的匹配構造函數不可行:需要 0 arguments,但提供了 1
void initState() {
currentState = new State(Room::rooms.front());
}
我讀過的其他問題/線程似乎說錯誤與構造函數重載或沒有默認構造函數有關。 這些聲明過去可以正常工作,我沒有更改它們,所以我不確定這里發生了什么。
對於后代,這里是我的一些房間 class (.h 文件):
#ifndef TEXTADV_ROOM_H
#define TEXTADV_ROOM_H
#include <string>
#include <forward_list>
#include <list>
#include "GameObject.h"
using std::string;
/**
* Represents a room (accessible location in the game).
*/
class Room {
public:
/**
* Constructs a new Room.
* @param _name Name of the room.
* @param _desc Description of the room.
*/
Room(const string *_name, const string *_desc);
/**
* List storing all rooms that have been registered via addRoom().
*/
static std::list<Room*> rooms;
/**
* Creates a new Room with the given parameters and register it with the static list.
* @param _name Name of the room.
* @param _desc Description of the room.
*/
static Room* addRoom(const string* _name, const string* _desc);
};
#endif //TEXTADV_ROOM_H
謝謝你。
std::list::front()
返回一個迭代器。 不是元素的(副本)。
您還必須首先檢查列表是否為空。
void initState() {
if (not Rooms::rooms.empty())
currentState = new State(Room::rooms.front());
}
此外,為 class 聲明構造函數會刪除默認構造函數。
您可以使用= default
將其添加回來
// foo.hpp
class foo {
int *p_, *k_;
public:
explicit foo(int*, int*);
foo() = default;
};
// foo.cpp
foo::foo(int *p, int *k)
: p_{ p }, k_{ k }
{}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.