【问题标题】:C++: Abstract classes inheritance and constructionC++:抽象类继承和构造
【发布时间】: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


【解决方案1】:

因为您通过 const 引用传递类,所以我假设您想复制它们。为此,您将需要额外的虚拟成员函数 clone,它将返回指向动态分配的对象副本的指针。

class func {
    ...
    virtual func* clone() const;
    ...
};

class polynom: public func {
    ...
    virtual polynom* clone() const override {
        return new polynom(n_, coefs_);
    }
    ...
};

class compfunc: public func {
    ...
    compfunc(const func& outter, const func& inner): outer_(outter.clone()), inner_(inner.clone()) {}
    ...
    virtual compfunc* clone() const override {
        ...
    }
};

这样您就可以复制传递的对象,而不管其动态类型如何。

【讨论】:

  • “因为你通过 const 引用传递类,我假设你想复制它们”。如果我见过一个,那是不合逻辑的。
猜你喜欢
  • 2015-08-06
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多