我主要有以下内容:
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/