C++ new operator. Creating a new instance
I'm having some trouble creating an object in C++. I create a class called Instruction, and I am trying to create a new instance, but I get compiler errors.
Class code:
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";
}
This is how I try to create a new object:
Instruction* inst;
inst = new Instruction("instruction33", 33);
I get the following compiler errors:
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开发者_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*)
You guys are correct. The error comes from this line of code:
instList.push_back(inst);
where instList is created like this:
list <Instruction> instList; //#include <list> is in the file
inst
is a pointer to an Instruction object and instList
is a list of Instruction objects. So when you try instList.push_back(inst)
it doesn't work (it expects a real object not the pointer to it). You should instead have instList.push_back(*inst)
.
I think you would be better of not dynamically creating the Instruction.
list <Instruction> instList;
instList.push_back(Instruction("instruction33", 33));
Notice there is no need to use new.
If you use new you should be deleting the pointer.
That adds a whole level of complexity that you are not ready for.
actually, it looks like your error message doesn't have anything to do with the code you pasted in your OP. I had a very good response ready to go about not passing const char * as a std::string& parameter, but that doesn't look like it's your issue. What you have posted isn't enough to pinpoint the problem.
There is nothing wrong with the code you pasted, the error from the message says to check functions.h on line 70.
Instead of:
instList.push_back(inst);
try this:
instList.push_back(*inst);
You're trying to put a pointer to an Instruction into a list of Instructions.
精彩评论