C++ 新运算符。创建一个新实例

标签 c++ class new-operator

我在用 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

最佳答案

inst 是指向 Instruction 对象的指针,instList 是 Instruction 对象的列表。所以当你尝试 instList.push_back(inst) 时它不起作用(它需要一个真实的对象而不是指向它的指针)。您应该使用 instList.push_back(*inst)

关于C++ 新运算符。创建一个新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736480/

相关文章:

c++ - 为什么程序不能正确地反转数组的值?

ios - 创建一个由变量标识的类

java - 如何在某个类中使用另一个类的方法?

c++ - 为什么 new[-1] 会产生 segfault,而 new[-2] 会抛出 bad_alloc?

c++ - 如何计算递归函数?

c++ - 通过 "this->member"访问 c++ 成员类比隐式调用 "member"更快/更慢

c++ - 指向字符串的指针大小与字符串大小的差异

c++ - 如何在 C++ 中实现 resize() 来改变动态成员数据的容量

c++ - 删除/释放由 malloc 分配并由 new 重用的内存

C++ 分配器 : operator new or placement new