2017-05-20 2 views
1

ここに私がしようとしていることの具体的な例があります。私は、この関数の終わりまでに作成されたオブジェクトの型を持つ必要があるので、文字列、ID、または式パラメータのいずれかである(まだ作成されていない)ものに格納することができます。私が直面している問題は、まだロジックを行っていない場合、作成するオブジェクトのタイプがわからないことです。ロジックを実行しているときにifステートメント内にオブジェクトを作成すると、それ以上存在しなくなります。私はここにリストされていない別のクラスの型パラメータのベクトルにオブジェクトを格納したい。コードも事前にオブジェクトをC++で作成しています

bool parameter(Predicate& pred)//look for the following: STRING | ID | expression 
{ 
    //store a parameter in this predicate 
    Parameter // <- I don't know which type of object to create yet!!!! 
    //create parameter 
    get_grammar_type(token, sfile); 
    token_type = token.Get_type(); 
    if(token_type == STRING) 
    { 
     //would create object of type string here 
     //can't create object here. It won't exist after. 
    } 
    else if(token_type == ID) 
    { 
    //would create object of ID string here 
      //can't create object here. It won't exist after. 
    } 
    if(expression(pred)) 
    { 
     //would create object of Expression here.can't create object here. It won't exist after. 
    } 
//store object in object pred here. Pred has a private member of a vector of type parameters within it. 
    return true; 
} 

#ifndef PARAMETER_H 
#define PARAMETER_H 
#include <string> 
#include <vector> 
#include "Predicate.h" 

using namespace std; 

class Parameter 
{ 

    public: 

    private: 
} 

class String : public Parameter 
{ 
    public: 
     insert_string(string in_string); 


    private: 
     string my_string; 

} 

class ID : public Parameter 
{ 
    public: 
     insert_id(string in_ID); 

    private: 
     string my_ID; 

}; 


class Expression : public Parameter 
{ 
    private: 
     Parameter left_parameter; 
     Parameter right_parameter; 
     string op; 

    public: 

}; 

#endif 

//の終わりに、私は、私は、彼らがまだ

+0

'C++ 'が' interface'sを持っているのかどうか分かりませんが、 'C#'でそれをやる方法です。後で正しい型にキャストできるように 'interface'オブジェクトと' enum'を持つ構造体を作成してください。 –

+0

@JamesHughes C++はそれをすべて持っているし、いくつか:) –

+0

多態性を使っていますか? – Peter

答えて

-1

あるどのような種類がわからない場合、私は表現クラスの左と右のパラメータを作成することができます方法を知りたいですこの場合、ポインタを使用することができます。 Parameter*変数をさらに作成し、if文の1つにデータ構造を動的に割り当て、そのポインタに代入します。たとえば:あなたは割り当て解除を心配させたくない場合は

Parameter *parameter = NULL; 
if(token_type == STRING) 
{ 
    parameter = (Parameter*) new String(); 
} 

smart pointersと手の込んだ何かをします。

関連する問題