C++ 模板和派生类,与函数不匹配



我尝试编译以下代码:

#include "Fraction.cpp"
#include "Pile.cpp"
#include "Plus.cpp"
#include <iostream>
using namespace std;
Nombre calcul(Element* tab [], int nbElement){
  Pile<Nombre> pile  = Pile<Nombre>(30);
  for(int i = 0 ; i < nbElement ; i++){
      if( tab[i]->getType() == "o" ){
        Fraction f = (*tab[i])(pile.pop(),pile.pop());
        pile.push(f);
      }
      else if(tab[i]->getType() == "n"){
        pile.push(*(tab[i]));
      }
  }
  return pile.pop();
}
int main(){
}

以下是所需的类:

分数.hpp:

#include <iostream>
#include "Element.cpp"
using namespace std;

class Fraction : public Nombre{
private:
  int nume;
  int deno;
  static int pgcd(int x, int y);
public:
  Fraction(int n, int d);
  Fraction(int n);
  int getNume() const;
  int getDeno() const;
  virtual string getType();
  Fraction operator+(const Fraction &) const;
  Fraction operator-(const Fraction &) const;
};
ostream &operator<<(ostream &os,const Fraction &f);
Fraction operator+(const int &n,const Fraction &f);

堆.hpp:

template <typename T> class Pile{
  private:
    int size;
    int top;
    T* stacktab;
  public:
    Pile<T>();
    Pile<T>(int s);
    bool isEmpty();
    bool isFull();
    bool push(T elt);
    T pop();
    void afficher(ostream &flux);
};

元素.cpp:

#include <string>
using namespace std;
class Element{
public:
  virtual string getType() = 0;
};

class Operateur : public Element{
public:
    virtual string getType() ;
};
class Nombre : public Element{
public:
    virtual string getType() ;
};
string Operateur::getType() {
  return "o";
}
string Nombre::getType() {
  return "n";
}

另外.cpp:

class Plus : public Operateur{
public:
  Fraction operator()(Fraction f1, Fraction f2);
};
class Moins : public Operateur{
public:
  Fraction operator()(Fraction f1, Fraction f2);
};
Fraction Plus::operator()(Fraction f1,Fraction f2){
  return f1 + f2;
}
Fraction Moins::operator()(Fraction f1, Fraction f2){
  return f1 - f2;
}

当我尝试编译此代码时,我收到 2 个错误:

1) error: no match for call to ‘(Element) (Nombre, Nombre)’
         Fraction f = (*tab[i])(pile.pop(),pile.pop());

在这里,*tab[i] 是 Element 上的指针,但实例应该是 Plus 或 Moins(它们都派生自 Operationur,Operationur 派生自 Element(。我理解这个问题:我只在 Plus 和 Moins 类中实现了 operator((,所以编译器在 Element 中找不到它,但我该如何解决这个问题?

2) error: no matching function for call to ‘Pile<Nombre>::push(Element&)’
         pile.push(*(tab[i]));
note: candidate: bool Pile<T>::push(T) [with T = Nombre]
template <typename T>  bool Pile<T>::push(T elt){
                             ^
note:   no known conversion for argument 1 from ‘Element’ to ‘Nombre’

我使用Pile,并尝试使用Element对象push((。由于Nombre是从Element派生的,我不应该使用Element对象而不是Nombre对象吗?

几个小时以来,我一直在寻找答案,但我仍然不明白。我觉得我没有理解一些非常基本的东西。

你需要

在元素中有一个virtual Fraction operator()(Fraction f1, Fraction f2);

但这不会那么容易,因为 Fraction 是从 Element 派生出来的,所以还没有被声明。 你可以试试virtual Element operator()(Element e1, Element e2);. 但是你会发现,从Plus和Moins返回非同质类型将是另一个问题。

您正在将非同质类型推到桩上。 那行不通。 尽管 Fraction 源自 Nombre,但它并不完全是 Nombre,并且会切片。

最新更新