C++ 继承-子类构造函数调用?

标签 c++ inheritance constructor object-slicing

我主要有以下内容:

Sum *sum = new Sum(Identifier("aNum1"), Identifier("aNum2"));

我的类(class)是:

class Table {
private:
    static map<string, int> m;    
public:
    static int lookup(string ident)
    {
        return m.find(ident)->second;
    }
    static void insert(string ident, int aValue)
    {
        m.insert(pair<string, int>(ident, aValue));
    }
};   

class Expression {
public:
    virtual int const getValue() = 0;
};

class Identifier : Expression {
private:
    string ident;
public:
    Identifier(string _ident) { ident = _ident; }
    int const getValue() { return Table::lookup(ident); }    
};

class BinaryExpression : public Expression {
protected:
    Expression *firstExp;
    Expression *secondExp;
public:
    BinaryExpression(Expression &_firstExp, Expression &_secondExp) {
        firstExp = &_firstExp;
        secondExp = &_secondExp;
    }
};

class Sum : BinaryExpression {
public:
    Sum(Expression &first, Expression &second) : BinaryExpression (first, second) {}
    int const getValue() 
    { 
        return firstExp->getValue() + secondExp->getValue();
    }
};

编译时出现以下错误:

没有匹配函数来调用'Sum::Sum(Identifier, Identifier)'

候选者是:Sum::Sum(Expression&, Expression&)

Identifier 类继承自 Expression,为什么会出现此错误?

最佳答案

问题是您正在将临时对象传递给构造函数,但构造函数需要一个-const 引用,而临时对象只能绑定(bind)到const 引用。

要修复它,请将参数类型更改为 Expression const&。顺便说一句,这与继承和多态性完全无关(但还需要 digivampire 的修复;我怀疑这只是一个错字)。

关于C++ 继承-子类构造函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7980621/

相关文章:

C++ 表达式必须是可修改的左值

java - 访问随机分配的对象

C++ 动态转换

ruby :kind_of?与 instance_of?与 is_a?

objective-c - Objective C - init 和构造函数之间的区别?

Java错误: constructor Transaction in class Transaction cannot be applied to given types

c++ - 为什么我的 RGB 转十六进制函数在传递颜色分量时返回 0?

c++ - 试图将一个点返回到一个二维字符数组

c++ - 删除 C 风格的 int vector 数组

javascript - 是否可以将构造函数作为类中的方法?