能够编译和运行.然而,当运行代码时,它不能打印我想打印的任何值

Able to compile and run. However, when runnig the code it can not print any value which i want to print

本文关键字:打印 运行 任何值 不能 想打 代码 编译 然而      更新时间:2023-10-16
#include <typeinfo>
#include <iostream>
#include <math.h>
template <typename T>
class Polynomial
{
private:
    Polynomial *termArray;
    //int capacity;
    //int terms;
    T coef,exp;
public:
    Polynomial()
    {   
            termArray = new Polynomial[3];
    };  
    ~Polynomial();
    void Print();
    void CreateTerm(const T coef, const int exp);
};
template <typename T>
Polynomial<T>::~Polynomial()
{
    delete []termArray;
}
template <typename T>
void Polynomial<T>::Print()
{
    for(int i=0;i<3;i++)
    std::cout << termArray[i].coef << " " << termArray[i].exp << std::endl; 
}
template <typename T>
void Polynomial<T>::CreateTerm(const T coef,const int exp)
{
    for(int i=0;i<3;i++)
    {   
            termArray[i].coef = coef;
            termArray[i].exp = exp;
    }   
}
int main()
{
    Polynomial<double> f,g;
    f.CreateTerm(-4.8,3);
    f.CreateTerm(2.9,2);
    f.CreateTerm(-3,0);
    std::cout << "f = ";
    f.Print();
    g.CreateTerm(4.3,4);
    g.CreateTerm(-8.1,0);
    g.CreateTerm(2.2,3);
    std::cout << "g = ";
    g.Print();
return 0;
}

与前面的主题一样,该代码可以编译和运行。然而,当运行代码时,它不能打印任何值,我想打印出来,去长睡眠。(虽然我输入了任何东西,但它没有响应我的输入)

如何修改打印的代码…

这是你的构造函数:

Polynomial()
{   
        termArray = new Polynomial[3];
};

当你创建一个新的多项式时,你的代码会在构造函数中创建3个新的多项式。对于这3个多项式中的每一个,您将创建另外3个!在这一点上总共有13个多项式对象。新的再加3。这将一直持续下去,直到内存耗尽。更具体地说,当你用完堆栈空间时,因为这些都是在那里分配的。

你的代码永远不会超过这一行,因为它会递归地调用构造函数:
termArray = new Polynomial[3];

其他需要考虑的事情:

  • 考虑添加另一个类Coefficient
  • 而不是Polynomial对象内的Polynomial对象的数组(相当字面上你的堆栈溢出错误),你会有一个Coefficient对象的数组在你的Polynomial对象。
  • 一个多项式可以有多于或少于3个系数/指数。
  • 如果你使用std::vector而不是数组,你可以简单地在你的类的create_term()中调用vector的push_back()方法来添加一个新的系数。
相关文章: