2015-12-10 98 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

相關問題