【发布时间】:2018-11-29 23:56:05
【问题描述】:
我需要构建一个包含 2 个对象的 dos 函数组合的 C++ 程序。 对象可以是多项式、有理函数或复合函数。
我有一个名为“func”的抽象类。我还有 2 个继承了 'func' 的类,分别命名为 'ratfunc' 和 'polynom'。 第三个类“compfunc”,也继承了“func”,它的构造函数头给了我。 Comfunc 从 'func' 类中接收 2 个抽象对象(通过引用),并需要将它们组合成一个新函数(语法:new compfunc(*outer,*inner).outer,inner are *func)
外部和内部可以是ratfunc、多项式或comfunc本身。
我的问题是如何在不使用模板和不知道对象类的情况下构建这样的构造函数。
编辑:
代码:
主要:
func* outer;
func* inner;
char* outer_name = strtok(func_value, ",");
char* inner_name = strtok(NULL, ",");
try{
outer = func_list.at(outer_name);
inner = func_list.at(inner_name);
func_list[string(outer_name)+"("+string(inner_name)+")"]=new
compfunc(*outer,*inner);
}
Func 类(抽象):
class func {
public:
func(); //constructor
func(const func& f); //copy constructor
virtual ~func();
protected:
bool flag; //values has been assigned, initialised to false in the constructor
};
多项式类:
class polynom : public func {
public:
polynom(); //default constructor
polynom(int n, int* coefs); //constructor
polynom(const polynom& pol); //copy constructor
~polynom(); //destrcutor
protected:
int n_; //order of the polynom
int* coefs_; //coefficients
};
Ratfunc 类:
class ratfunc : public func{
public:
ratfunc(const polynom& p, const polynom& q); //constructor
ratfunc(const ratfunc& rf); //copy constructor
~ratfunc(); //desctrcutor
protected:
polynom p_; //down
polynom q_; //up
};
复合函数:
class compfunc : public func{
public:
compfunc(const func& outter, const func& inner);
compfunc(const compfunc& cf); //copy constructor
~compfunc(); //destrcutor
protected:
func* outer_;
func* inner_;
};
谢谢!!
【问题讨论】:
-
只发布一个您正在描述的代码的小示例比尝试描述您的代码要短得多,也更清晰。
-
^ 这个,你没有说这两个函数应该如何组合。应该是
compfunc(x) = outer(inner(x))吗? -
我添加了相关的代码片段。谢谢
-
请阅读minimal reproducible example。很难从您展示的片段中理解任何意义。
-
在
func中有任何用户定义的构造函数没有多大意义。然而,在那里至少拥有一个虚拟功能确实很有意义。没有一个人就不可能完成你的任务。
标签: c++ class constructor abstract-class