【发布时间】:2009-11-15 03:31:24
【问题描述】:
我在用 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
【问题讨论】:
-
我在代码中添加了问题所在。当我尝试将指令添加到指令列表时会发生这种情况。
-
你用
g++编译吗?我尝试用gcc编译这段代码,我得到了类似的错误。 -
我把like改成list
instList;它现在编译得很好。谢谢 -
不。您应该将其更改回指令列表。 AND 你不应该首先动态地创建指令。我敢打赌你没有任何你需要的删除。
标签: c++ class new-operator