我有两个类:“transition”类和“state”类。我想在状态类中存储转换向量,因此我需要在“state.h”中包含“transition.h”。另一方面,在转换过程中,我想存储一个指向状态类对象的指针,因此我需要在“transition.h”中包含“state.h”。
在转换类的方法中,我不使用状态类的任何方法,因此转换需要了解类状态的唯一信息是它存在并具有一些公共方法。但问题是,当我尝试在状态类方法内部调用转换构造函数时,它会给出错误,指出转换类对象没有匹配的构造函数。
所以,这里是转换构造函数:
transition(std::shared_ptr<state>& from_state, std::shared_ptr<state>& to_state,
std::unique_ptr<matcher>&& transition_matcher);
transition(std::shared_ptr<state>& from_state, std::shared_ptr<state>& to_state,
std::unique_ptr<matcher>&& transition_matcher, std::vector<size_t>& end_groups, std::vector<size_t>& start_groups);
在状态类方法内部,我尝试构造一个转换对象:
void state::add_transition(std::shared_ptr<state> &to, std::unique_ptr<matcher> &&transition_matcher) {
transition t{std::make_shared<state>(*this), to, std::move(transition_matcher)};
transitions.push_back(t);
}
上面的代码块给出了一个错误:
No matching constructor for initialization of 'transition'
它建议使用这些参数作为转换构造函数:
int& from_state, int& to_state, std::unique_ptr<matcher>&& transition_matcher
我想这是因为这种循环依赖性而发生的,但我不知道到底为什么。
我尝试使用前向声明并将
class state;
放在过渡类声明之前。结果是,当我尝试如上所述构造转换对象时,它会找到相应的构造函数,让我构造这个对象,然后将其推回向量。但是我尝试以这种方式使用 emplace_back() :
void state::add_transition(std::shared_ptr<state> &to, std::unique_ptr<matcher> &&transition_matcher) {
transitions.emplace_back(std::make_shared<state>(*this), to, std::move(transition_matcher));
}
我收到这句话的错误
In template: no matching function for call to 'construct_at' error occurred here in instantiation of function template specialization 'std::allocator_traits<std::allocator<transition>>::construct<transition, std::shared_ptr<state>, std::shared_ptr<state> &, std::unique_ptr<matcher>>' requested here in instantiation of function template specialization 'std::vector<transition>::emplace_back<std::shared_ptr<state>, std::shared_ptr<state> &, std::unique_ptr<matcher>>' requested here candidate template ignored: substitution failure [with _Tp = transition, _Args = <std::shared_ptr<state>, std::shared_ptr<state> &, std::unique_ptr<matcher>>]: no matching constructor for initialization of 'transition'
有人可以解释一下为什么第一种情况下有问题,为什么第二种情况下 emplace_back() 有问题吗?
你说
另一方面,在转换过程中我想存储一个指向 状态类对象,因此我需要在中包含“state.h” “过渡.h”。
这是不正确的,您所需要的只是一个前向声明
class State;
这样做而不是
#include "state.h"
将解决你的问题。