【发布时间】:2018-12-24 06:18:45
【问题描述】:
在我们的学习书中有一个关于对象函数的问题。 c++中有一段代码,问题要我们填补空白。代码如下
template <typename Arg, typename Ret>
class FuncObj {
public:
typedef Arg argType;
typedef Ret retType;
virtual Ret operator()(Arg) = 0;
};
class DivideBy : public FuncObj<int, double> {
protected:
int divisor;
public:
DivideBy(int d) {
this->divisor = d;
}
double operator()(int x) {
return x/((double)divisor);
}
};
class Truncate : public FuncObj<double, int> {
public:
int operator()(double x) {
return (int) x;
}
};
template < typename Ftype , typename Gtype >
class Compose : public FuncObj <typename Gtype :: argType, typename Ftype :: retType > {
protected:
Ftype *f; Gtype *g;
public:
Compose(Ftype f,Gtype g) {
--------- =f;
--------- =g;
}
---------- operator()(____________x) {
return (_________)((________)(__________)); }
};
理想的结果是
void main() {
DivideBy *d = new DivideBy(2);
Truncate *t = new Truncate();
Compose<DivideBy, Truncate> *c1 = new Compose<DivideBy,Truncate>(d,t);
Compose<Truncate, DivideBy> *c2 = new Compose<Truncate, DivideBy>(t,d);
cout << (*c1)(100.7) << endl; // Prints 50.0
cout << (*c2)(11) << endl; // Prints 5
}
我真的不知道如何完成这段代码,那么我们应该使用 c++ 的什么特性或概念来完成这个工作呢?如果有关于这个主题的进一步研究的链接,请写下来。 谢谢。
【问题讨论】:
-
这个->f = &f;这->g = &g; ?
-
老实说,你的学习书不值得印在纸上。作者甚至没有费心去验证这个重要的代码是否没有错误。
-
附带说明:删除所有
new和*,它们是不需要的,并且由于您不删除它们而导致内存泄漏。更多详情请见stackoverflow.com/q/184537/2466431 -
代码非常不好!这本书的作者不知道构造函数是如何工作的!在构造函数的主体中覆盖而不是在初始化列表中使用初始化或多或少是失败的。也许这些类型不是默认可构造的,并且所有代码都停止了。我们在哪里可以找到所有不需要的“新”的“删除”?请拿一本更好的书告诉你的老师,这种代码质量永远不能用于生产!
标签: c++ c++11 inheritance