2015-12-10 95 views
0

我有一个叫State的类,它有一个shared_ptr,weak_ptr和一个int作为它的字段。我还有另一个叫Automata的课程,它有一个shared_ptr到一个州。我使用State来模仿NFA中的状态。 Automata是NFA中的州的链接列表。和状态链接shared_ptr,自我循环由weak_ptr表示。shared_ptr编译器错误无效转换

class State { 
    public: 
     // ptr to next state 
     std::shared_ptr<State> nextState; 
     // ptr to self 
     std::weak_ptr<State> selfLoop; 
     // char 
     int regex; 
     // Constructor 
     State(const int c) : regex(c){} 
     // Destructor 
     ~State(); 
}; 
#define START 256 

#define FINAL 257 

class Automata { 
    private: 
     std::shared_ptr<State> start; 
    public: 
     // Constructor, string should not be empty 
     Automata(const std::string &str); 
     // Destructor 
     ~Automata(); 
     // Determine a string matched regex 
     bool match(const std::string &str); 
}; 

Automata构造基本上发生在一个正则表达式,并将其转换为NFA(它的工作原理见这个,如果你有兴趣:https://swtch.com/~rsc/regexp/regexp1.html)。

编译Automata的构造函数时,编译器错误发生。它如下

Automata::Automata(const string &str) { 
    start = make_shared<State>(new State(START)); // Error is here, START defined above 
    for (loop traversing str) { 
     //add more states to start 
    } 
} 

我,指出

// A lot gibbrish above 
Automata.cc:7:45: required from here 
/usr/include/c++/4.8/ext/new_allocator.h:120:4: error: invalid conversion 
from ‘State*’ to ‘int’ [-fpermissive] 
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); } 
^ 
In file included from Automata.h:4:0, 
        from Automata.cc:2: 
State.h:18:2: error: initializing argument 1 of ‘State::State(int)’ [-fpermissive] 
State(const int c); 
^ 

不知道我做错了什么错误来实现。我对shared_ptr完全陌生,所以我不知道这是make_shared的问题还是State构造函数的错误?你能帮我解决这个问题吗?

+1

使用'make_shared'时,不应该使用new。 'make_shared'完美地将它的参数转发给'State'构造函数,这就是你的错误发生的地方(它转发一个'State'指针并且期望一个int)。您应该使用与构建“State”对象时相同的参数。 –

回答

3

你不想写:

Automata::Automata(const string &str) { 
    start = make_shared<State>(START); // make_shared will call new internally 
    for (loop traversing str) { 
     //add more states to start 
    } 
} 

+0

谢天谢地!你太棒了! – Mandary

相关问题