我正在尝试创建一些使用继承类的重载算术运算符,如下所示:
class Block {
public:
Block() {}
virtual double Value() {};
};
class Constant : public Block {
public:
Constant(double v) { value = v; }
virtual double Value() { return value; }
private:
double value;
};
class Add : public Block {
public:
Add(Block &a, Block &b) { value1 = &a; value2 = &b; }
virtual double Value() { return value1->Value() + value2->Value(); }
private:
Block *value1;
Block *value2;
};
Block operator + (Block &a, Block &b) {
return new Add(a, b);
}
int main() {
Constant a(5.0);
Constant b(6.0);
printf("%.3f", (a+b).Value());
}
但我得到以下信息:error: conversion from 'Add*' to non-scalar type 'Block' requested
这是我第一次在 C++ 中使用 OOP,所以我的想法是否可行?