ago*_*uil 2 c++ inheritance constructor object-slicing
我主要有以下内容:
Sum *sum = new Sum(Identifier("aNum1"), Identifier("aNum2"));
Run Code Online (Sandbox Code Playgroud)
我的课程是:
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();
}
};
Run Code Online (Sandbox Code Playgroud)
当我编译它时,我收到以下错误:
没有用于调用'Sum :: Sum(Identifier,Identifier)'的匹配函数
候选人是:Sum :: Sum(Expression&,Expression&)
Identifier类继承自Expression,为什么我会收到此错误?
问题是要传递的临时给你的构造函数,但构造函数需要一个非 - const参考,而临时对象只能绑定到const引用.
要修复它,请将参数类型更改为Expression const&.顺便说一下,这与继承和多态完全无关(但也需要digivampire的修复;我怀疑这只是一个错字).
| 归档时间: |
|
| 查看次数: |
670 次 |
| 最近记录: |