我在使用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
答案 0 :(得分:4)
inst
是指向对象的指针,instList
是指令对象的列表。所以当你尝试instList.push_back(inst)
它不起作用时(它期望一个真实的对象而不是它的指针)。你应该改为instList.push_back(*inst)
。
答案 1 :(得分:4)
我认为你最好不要动态创建指令。
list <Instruction> instList;
instList.push_back(Instruction("instruction33", 33));
请注意,无需使用新的 如果你使用new,你应该删除指针 这增加了你尚未准备好的整体复杂程度。
答案 2 :(得分:0)
实际上,您的错误消息看起来与您在OP中粘贴的代码没有任何关系。我有一个非常好的响应准备好不要传递const char *作为std :: string&amp;参数,但看起来不是你的问题。您发布的内容不足以查明问题。
答案 3 :(得分:0)
您粘贴的代码没有任何问题,消息中的错误表示检查第70行的functions.h。
答案 4 :(得分:0)
而不是:
instList.push_back(inst);
试试这个:
instList.push_back(*inst);
您正试图将指令指针放入指令列表中。