0

C++ でオブジェクトを作成するのに問題があります。Instruction というクラスを作成し、新しいインスタンスを作成しようとしていますが、コンパイラ エラーが発生します。

クラスコード:

class Instruction{

  protected:
    string name;
    int value;

  public:
    Instruction(string _name, int _value);
    ~Instruction();
    void setName(string _name);
    void setValue(int _value);
    string getName();
    int getValue();
    virtual void execute();
};



//constructor
inline Instruction::Instruction(string _name, int _value){
    name = _name;
    value = _value;
}
//destructor
inline Instruction::~Instruction(){
    //name = "";
    //value = 0;
}
inline void Instruction::setName(string _name){
     name = _name;
}

inline void Instruction::setValue(int _value){
    value = _value;
}

inline string Instruction::getName(){
       return name;
}

int Instruction::getValue(){
    return value;
}
inline void Instruction::execute(){
    cout << "still have to implement";
}

これは私が新しいオブジェクトを作成しようとする方法です:

Instruction* inst;
inst = new Instruction("instruction33", 33);

次のコンパイラ エラーが発生します。

functions.h:70: error: no matching function for call to ‘operator new(unsigned int, std::string&, int&)’
/usr/include/c++/4.3/new:95: note: candidates are: void* operator new(size_t)
/usr/include/c++/4.3/new:99: note:                 void* operator new(size_t, const std::nothrow_t&)
/usr/include/c++/4.3/new:105: note:                 void* operator new(size_t, void*)

あなたたちは正しいです。エラーは、次のコード行から発生します。

instList.push_back(inst);

instList は次のように作成されます。

list <Instruction> instList;  //#include <list> is in the file
4

5 に答える 5

4

命令を動的に作成しない方がよいと思います。

list <Instruction> instList;

instList.push_back(Instruction("instruction33", 33));

new を使用する必要がないことに注意してください。
new を使用する場合は、ポインターを削除する必要があります。
これにより、準備ができていないレベルの複雑さが追加されます。

于 2009-11-15T07:31:39.293 に答える
4

instInstruction オブジェクトへのポインターであり、Instruction オブジェクトinstListのリストです。そのため、試しinstList.push_back(inst)てみても機能しません (ポインターではなく、実際のオブジェクトが必要です)。代わりにinstList.push_back(*inst).

于 2009-11-15T04:04:39.743 に答える
0

それ以外の:

instList.push_back(inst);

これを試して:

instList.push_back(*inst);

命令へのポインターを命令のリストに入れようとしています。

于 2009-11-15T05:16:00.820 に答える
0

貼り付けたコードに問題はありません。メッセージのエラーは、70 行目の functions.h を確認するように指示しています。

于 2009-11-15T03:47:55.983 に答える
0

実際、エラー メッセージは、OP に貼り付けたコードとは何の関係もないようです。const char * を std::string& パラメーターとして渡さないという非常に良い応答がありましたが、それはあなたの問題ではないようです。あなたが投稿したものは、問題を特定するのに十分ではありません。

于 2009-11-15T03:45:27.370 に答える