C++类继承问题

标签 c++ inheritance class copy-constructor virtual-copy

你好,我有两个类,一个叫做 Instruction,一个叫做 LDI,它继承自 instruction 类。

class Instruction{

  protected:
    string name;
    int value;

  public:
    Instruction(string _name, int _value){ //constructor
        name = _name;
        value = _value;
    }
    ~Instruction(){}
    Instruction (const Instruction &rhs){
        name = rhs.name;
        value = rhs.value;
    }
    void setName(string _name){
        name = _name;
    }
    void setValue(int _value){
        value = _value;
    }
    string getName(){
        return name;
    }
    int getValue(){
        return value;
    }
    virtual void execute(){}
    virtual Instruction* Clone() { 
        return new Instruction(*this); 
    }
};
/////////////end of instruction super class //////////////////////////

class LDI : public Instruction{

    void execute(){
        //not implemented yet
    }
    virtual Instruction* Clone(){
        return new LDI(*this);
    }
};

然后我创建一个 Instruction 类型的指针,并尝试指向一个 LDI 类型的新实例。

Instruction* ptr;
ptr = new LDI("test", 22);

我收到以下编译器错误。知道我做错了什么吗?

functions.h:71: error: no matching function for call to ‘LDI::LDI(std::string&, int&)’
classes.h:54: note: candidates are: LDI::LDI()
classes.h:54: note:                 LDI::LDI(const LDI&)

最佳答案

代码:new LDI(name, val) 特别指出“使用 nameval 调用 LDI 构造函数。”

没有采用 name/val 的 LDI 构造函数。 事实上,我根本没有看到 LDI 的构造函数。

如果你想使用基类的构造函数,方法如下:

public LDI(string _name, int _value) // Public constructor for LDI
    : Instruction(_name, _value)     // Delegate to the base-class constructor
{
    // Do more LDI-specific construction here
}

关于C++类继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736745/

相关文章:

java - JAVA中的对象分层调用

PHP:在类外部或构造函数中定义常量?

.net - 如何重新加载经常崩溃的第 3 方 DLL

c++ - 如何忽略 Windows 7 中的 TCP PSH 位?

c++ - 如何在OpenGL中编写自动分配纹理单元的类或函数

javascript - 子类化 JavaScript 数组 - 构造函数参数未传递给数组

Python 类实例 __dict__ 不包含所有实例变量。为什么?

c++ - 生命游戏继续边界

C# 在运行时选择重载方法

java - 将多个对象合并为多种格式